【问题标题】:Electron app has multiple background services running and don't stop on exitElectron 应用程序有多个后台服务正在运行,并且在退出时不会停止
【发布时间】:2021-01-16 01:41:02
【问题描述】:

我刚刚构建了我的第一个 Electron 应用程序。但我注意到我的应用程序的 3 项服务随时在后台运行。当应用被全局键盘快捷键激活时,一个实例会移动到活动应用部分。

退出时,只有一个实例消失,而其他两个继续运行。如果不从任务管理器手动停止这些服务,我将无法再次启动应用程序。

app.js

const { app, BrowserWindow, globalShortcut } = require("electron");
const path = require("path");
const url = require("url");

let win = null;

var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
  // Someone tried to run a second instance, we should focus our window.
  if (win) {
    win.show();
  }
});

if (shouldQuit) {
  app.quit();
  return;
}

app.on("ready", () => {

win = new BrowserWindow({
    width: 1000,
    height: 600,
    transparent: true,
    frame: false
});

win.on("close", () => {
    win = null;
});

win.loadURL(
    url.format({
        pathname: path.join(__dirname, "app", "index.html"),
        protocol: "file",
        slashes: true
    })
);

win.once('ready-to-show', () => {
    win.show()
});

win.on("blur", () => {
    win.hide();
});

win.on('window-all-closed', () => {
    globalShortcut.unregisterAll();
    if (process.platform !== 'darwin') {
        app.quit()
    }
});

const ret = globalShortcut.register('CommandOrControl+L', () => {
    if(win == null) {
        globalShortcut.unregisterAll();
        return;
    }
    win.show();
});

if (!ret) {
    console.log('registration failed')
}

app.on('will-quit', () => {
    // Unregister all shortcuts.
    globalShortcut.unregisterAll();
});

app.on('before-quit', () => {
    win.removeAllListeners('close');
    globalShortcut.unregisterAll();
    win.close();
});

});

我之前遇到的错误是关闭时GlobalShortcut没有注销,所以我将它添加到before-quitwindow-all-close事件中。这样就解决了。

编辑: 上述问题仅发生在生产代码上。在开发过程中,所有 3 个实例都关闭在一起。我正在使用 Windows 10 和 Electron 1.6.11。

【问题讨论】:

    标签: node.js service window electron


    【解决方案1】:

    只需将此添加到包含电子模块的主 javascript 文件中

    app.on('window-all-closed', () => {
      app.quit()
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 2014-03-25
      • 2013-01-28
      • 2018-12-11
      相关资源
      最近更新 更多