index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const { Tray, Menu, shell } = require('electron');
  2. const path = require('path');
  3. const Ps = require('ee-core/ps');
  4. const Log = require('ee-core/log');
  5. const Electron = require('ee-core/electron');
  6. const Conf = require('ee-core/config');
  7. /**
  8. * 托盘插件
  9. * @class
  10. */
  11. class TrayAddon {
  12. constructor(app) {
  13. this.app = app;
  14. this.tray = null;
  15. }
  16. /**
  17. * 创建托盘
  18. */
  19. create () {
  20. // 开发环境,代码热更新开启时,会导致托盘中有残影
  21. if (Ps.isDev() && Ps.isHotReload()) return;
  22. Log.info('[addon:tray] load');
  23. const app = this.app;
  24. const cfg = Conf.getValue('addons.tray');
  25. const { mainWindow } = Electron;
  26. // 托盘图标
  27. let iconPath = path.join(Ps.getHomeDir(), cfg.icon);
  28. // 托盘菜单功能列表
  29. let trayMenuTemplate = [
  30. {
  31. label: '显示',
  32. click: function () {
  33. mainWindow.show();
  34. }
  35. },
  36. {
  37. label: '退出',
  38. click: function () {
  39. app.appQuit();
  40. }
  41. }
  42. ]
  43. // 点击关闭,最小化到托盘
  44. mainWindow.on('close', (event) => {
  45. const extraObj = Electron.extra;
  46. if (extraObj.closeWindow == true) {
  47. return;
  48. }
  49. mainWindow.hide();
  50. event.preventDefault();
  51. });
  52. // 实例化托盘
  53. this.tray = new Tray(iconPath);
  54. this.tray.setToolTip(cfg.title);
  55. const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
  56. this.tray.setContextMenu(contextMenu);
  57. // 使用默认浏览器打开链接
  58. mainWindow.webContents.setWindowOpenHandler(({ url }) => {
  59. shell.openExternal(url);
  60. return { action: 'deny' }
  61. })
  62. }
  63. }
  64. TrayAddon.toString = () => '[class TrayAddon]';
  65. module.exports = TrayAddon;