如何在电子 js 中运行后台服务?

Hit*_*oni 7 javascript node.js electron

如何使用电子实现后台服务。

我遇到了麻烦,谁能告诉我如何使用即使在关闭应用程序后仍能运行的电子启动后台服务。我尝试了很多解决方案,但所有解决方案都在关闭应用程序后停止服务。

yay*_*aya 6

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

"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;
});
Run Code Online (Sandbox Code Playgroud)


小智 3

Electron 并非设计为在后台运行。如果您要关闭应用程序,它将终止与其相关的所有进程。Electron仅用于提供GUI层。毕竟它是混合应用程序,它不与核心操作系统服务交互以像后台服务一样运行。

除此之外还有两个选择:

  1. 如果您使用其他东西(例如节点或 .net 应用程序)编写服务,那么您可能可以使用 Electron 与该服务交互(通过捆绑的 Node 访问 Windows API)。
  2. 创建系统托盘等功能。最小化应用程序到系统托盘。

参考链接