NodeJS - 一分钟后电子托盘图标消失

Pau*_*eck 2 javascript trayicon node.js electron

老实说,我不知道发生了什么。

我一直在关注该图标,几分钟后它就消失了。不,它不会转到时钟附近的箭头:

图标丢失

这是我的图标出现(红色爆炸):

在此处输入图片说明

我不知道如何调试图标是否存在但为空,或者是否有事件触发它隐藏,或者托盘进程是否由于错误而自行关闭。控制台或我的应用程序中没有任何反应。

有人可以帮忙吗?以下是我的全文index.js

const {app, BrowserWindow, Tray, Menu} = require('electron');
const path = require('path');

var win = '',
    iconpath = path.join(__dirname, '/libs/img/icon.ico');

// Create the browser window
function createWindow () {

  // BrowserWindow size
  win = new BrowserWindow({
    width: 800,
    height: 720,
    webPreferences: {
      nodeIntegration: true
    }
  });

  // tray menu
  var contextMenu = Menu.buildFromTemplate([
    {
        label: 'Show app', click: function () {
            win.show()
        }
    },
    {
        label: 'Quit', click: function () {
            app.isQuiting = true;
            app.quit();
        }
    }
  ]);

  // Creates tray menu with tray icon
  var appIcon = new Tray(iconpath);
  // Define menu
  appIcon.setContextMenu(contextMenu);

  win.on('close', function () {
    app.isQuiting = true;
    app.quit();
  });

  // Load the index.html of the app
  win.loadFile('./view/index.html');
}

app.on('ready', createWindow);
Run Code Online (Sandbox Code Playgroud)

小智 5

这是一个众所周知的与垃圾收集相关的问题,在Electron FAQ页面中提到:

几分钟后,我的应用程序的窗口/托盘消失了。

因此,快速解决方法是将appIcon变量的声明从createWindow函数中移出,win例如在变量旁边:

const {app, BrowserWindow, Tray, Menu} = require('electron');
const path = require('path');

var win = '',
    appIcon = null,
    iconpath = path.join(__dirname, '/libs/img/icon.ico');

// Create the browser window
function createWindow () {

  // BrowserWindow size
  win = new BrowserWindow({
    width: 800,
    height: 720,
    webPreferences: {
      nodeIntegration: true
    }
  });

  // tray menu
  var contextMenu = Menu.buildFromTemplate([
    {
        label: 'Show app', click: function () {
            win.show()
        }
    },
    {
        label: 'Quit', click: function () {
            app.isQuiting = true;
            app.quit();
        }
    }
  ]);

  // Creates tray menu with tray icon
  appIcon = new Tray(iconpath);
  // Define menu
  appIcon.setContextMenu(contextMenu);

  win.on('close', function () {
    app.isQuiting = true;
    app.quit();
  });

  // Load the index.html of the app
  win.loadFile('./view/index.html');
}

app.on('ready', createWindow);
Run Code Online (Sandbox Code Playgroud)