gpt4 book ai didi

javascript - 如何在 electron js 中运行后台服务?

转载 作者:搜寻专家 更新时间:2023-10-31 23:51:27 28 4
gpt4 key购买 nike

如何使用electron实现后台服务。

i'm having a trouble can anyone tell me how to start a background service using electron which runs even after closing the app. i have tried many solutions but all of them stop the service after closing the app.

最佳答案

您可以使用托盘。这是一个例子(source):

"use strict";

// [run the app]
// $ npm install electron
// $ ./node_modules/.bin/electron .

const {app, nativeImage, Tray, Menu, BrowserWindow} = require("electron");

let top = {}; // prevent gc to keep windows

app.once("ready", ev => {
top.win = new BrowserWindow({
width: 800, height: 600, center: true, minimizable: false, show: false,
webPreferences: {
nodeIntegration: false,
webSecurity: true,
sandbox: true,
},
});
top.win.loadURL("https://google.com/");
top.win.on("close", ev => {
//console.log(ev);
ev.sender.hide();
ev.preventDefault(); // prevent quit process
});

// empty image as transparent icon: it can click
// see: https://electron.atom.io/docs/api/tray/
top.tray = new Tray(nativeImage.createEmpty());
const menu = Menu.buildFromTemplate([
{label: "Actions", submenu: [
{label: "Open Google", click: (item, window, event) => {
//console.log(item, event);
top.win.show();
}},
]},
{type: "separator"},
{role: "quit"}, // "role": system prepared action menu
]);
top.tray.setToolTip("hello electrol");
//top.tray.setTitle("Tray Example"); // macOS only
top.tray.setContextMenu(menu);

// Option: some animated web site to tray icon image
// see: https://electron.atom.io/docs/tutorial/offscreen-rendering/
top.icons = new BrowserWindow({
show: false, webPreferences: {offscreen: true}});
top.icons.loadURL("https://trends.google.com/trends/hottrends/visualize");
top.icons.webContents.on("paint", (event, dirty, image) => {
if (top.tray) top.tray.setImage(image.resize({width: 16, height: 16}));
});
});
app.on("before-quit", ev => {
// BrowserWindow "close" event spawn after quit operation,
// it requires to clean up listeners for "close" event
top.win.removeAllListeners("close");
// release windows
top = null;
});

关于javascript - 如何在 electron js 中运行后台服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45481216/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com