系统能力集成

本章目标

  • 掌握桌面应用最常用的系统能力:菜单、托盘、通知、快捷键、文件对话框。
  • 能实现自定义协议唤起、开机自启、电源状态监听。
  • 理解自动更新的完整链路:检查、下载、安装、回滚。
  • 知道每个能力在 Windows/macOS 上的差异与常见坑。

能力总览

这些能力全部在主进程使用,渲染进程通过 IPC 请求。

应用菜单

1// src/main/system/menu.ts
2import { app, Menu, BrowserWindow, shell } from 'electron';
3
4export function installApplicationMenu(getWindow: () => BrowserWindow | null): void {
5  const isMac = process.platform === 'darwin';
6
7  const template: Electron.MenuItemConstructorOptions[] = [
8    ...(isMac
9      ? [
10          {
11            label: app.name,
12            submenu: [
13              { role: 'about' as const },
14              { type: 'separator' as const },
15              { role: 'hide' as const },
16              { role: 'hideOthers' as const },
17              { role: 'unhide' as const },
18              { type: 'separator' as const },
19              { role: 'quit' as const },
20            ],
21          },
22        ]
23      : []),
24    {
25      label: '文件',
26      submenu: [
27        {
28          label: '打开文件…',
29          accelerator: 'CommandOrControl+O',
30          click: () => getWindow()?.webContents.send('menu:open-file'),
31        },
32        { type: 'separator' },
33        isMac ? { role: 'close' } : { role: 'quit' },
34      ],
35    },
36    {
37      label: '编辑',
38      submenu: [
39        { role: 'undo' },
40        { role: 'redo' },
41        { type: 'separator' },
42        { role: 'cut' },
43        { role: 'copy' },
44        { role: 'paste' },
45        { role: 'selectAll' },
46      ],
47    },
48    {
49      label: '视图',
50      submenu: [
51        { role: 'reload' },
52        { role: 'toggleDevTools' },
53        { type: 'separator' },
54        { role: 'resetZoom' },
55        { role: 'zoomIn' },
56        { role: 'zoomOut' },
57        { type: 'separator' },
58        { role: 'togglefullscreen' },
59      ],
60    },
61    {
62      label: '帮助',
63      submenu: [
64        {
65          label: '官方网站',
66          click: () => shell.openExternal('https://www.electronjs.org/'),
67        },
68      ],
69    },
70  ];
71
72  Menu.setApplicationMenu(Menu.buildFromTemplate(template));
73}

平台差异:

  • macOS 第一个菜单必须是应用菜单,系统会自动补充「关于/服务/隐藏/退出」等行为。
  • Windows/Linux 菜单挂在每个窗口上,没有应用菜单概念。
  • role 让 Electron 使用系统标准行为与本地化文案,优先使用 role 而不是自己实现。

系统托盘

1// src/main/system/tray.ts
2import { app, Menu, Tray, nativeImage, BrowserWindow } from 'electron';
3import path from 'node:path';
4
5let tray: Tray | null = null;
6
7export function createTray(getWindow: () => BrowserWindow | null): void {
8  const iconPath = path.join(__dirname, '../../resources/trayTemplate.png');
9  const image = nativeImage.createFromPath(iconPath);
10  image.setTemplateImage(true); // macOS 自动适配深浅色
11
12  tray = new Tray(image);
13  tray.setToolTip('My App');
14
15  const menu = Menu.buildFromTemplate([
16    {
17      label: '显示主窗口',
18      click: () => {
19        const win = getWindow();
20        win?.show();
21        win?.focus();
22      },
23    },
24    { type: 'separator' },
25    { label: '退出', click: () => app.quit() },
26  ]);
27
28  tray.setContextMenu(menu);
29
30  tray.on('click', () => {
31    const win = getWindow();
32    if (win?.isVisible()) {
33      win.hide();
34    } else {
35      win?.show();
36    }
37  });
38}
39
40app.on('before-quit', () => {
41  tray?.destroy();
42  tray = null;
43});

注意事项:

  • macOS 使用 Template 图片(文件名以 Template 结尾),系统会自动反色。
  • Windows 托盘图标建议提供多尺寸(16/20/24/32),高 DPI 下才清晰。
  • 托盘常驻应用要明确「关闭窗口」与「退出应用」的区别,避免用户找不到退出入口。
  • Tray 必须在 app.whenReady() 之后创建。

通知

1// src/main/system/notification.ts
2import { app, Notification } from 'electron';
3
4app.setAppUserModelId('com.example.myapp'); // Windows 通知必需
5
6export function notify(title: string, body: string, onClick?: () => void): void {
7  if (!Notification.isSupported()) return;
8
9  const notification = new Notification({
10    title,
11    body,
12    silent: false,
13  });
14
15  notification.on('click', () => onClick?.());
16  notification.show();
17}

差异:

平台注意点
Windows必须设置 AppUserModelId,且应用需要正确安装(开始菜单快捷方式)
macOS首次通知会请求权限,用户拒绝后需引导到系统设置
Linux依赖桌面环境的通知服务,部分环境不支持点击回调

全局快捷键

1// src/main/system/shortcut.ts
2import { app, globalShortcut, BrowserWindow } from 'electron';
3
4export function registerShortcuts(getWindow: () => BrowserWindow | null): void {
5  const ok = globalShortcut.register('CommandOrControl+Shift+K', () => {
6    const win = getWindow();
7    if (!win) return;
8    if (win.isVisible()) {
9      win.hide();
10    } else {
11      win.show();
12      win.focus();
13    }
14  });
15
16  if (!ok) {
17    console.warn('快捷键注册失败,可能被其他应用占用');
18  }
19}
20
21app.on('will-quit', () => {
22  globalShortcut.unregisterAll();
23});

原则:

  • 只注册少量核心快捷键,冲突概率随数量上升。
  • 注册失败要能降级,不能影响应用启动。
  • 退出时注销,避免残留占用。
  • 不要抢占系统常用快捷键(如 Command+Space、Alt+Tab)。

文件对话框与文件系统

1// src/main/system/dialog.ts
2import { dialog, BrowserWindow } from 'electron';
3import fs from 'node:fs/promises';
4
5export async function pickAndReadFile(win: BrowserWindow): Promise<string | null> {
6  const result = await dialog.showOpenDialog(win, {
7    title: '选择配置文件',
8    properties: ['openFile'],
9    filters: [
10      { name: 'JSON', extensions: ['json'] },
11      { name: '所有文件', extensions: ['*'] },
12    ],
13  });
14
15  if (result.canceled || result.filePaths.length === 0) return null;
16
17  return fs.readFile(result.filePaths[0], 'utf-8');
18}

保存对话框:

1const { canceled, filePath } = await dialog.showSaveDialog(win, {
2  defaultPath: 'report.csv',
3  filters: [{ name: 'CSV', extensions: ['csv'] }],
4});
5
6if (!canceled && filePath) {
7  await fs.writeFile(filePath, csvContent, 'utf-8');
8}

原则:

  • 文件读写放在主进程,渲染进程只拿结果。
  • 打开用户选择的文件时,路径来自系统对话框,可信度较高;但仍要防止后续用拼接路径造成越权。
  • 大文件使用流式读写,不要一次性读入内存。

自定义协议与深链接

自定义协议用于「从浏览器或其他应用唤起本应用」,例如 myapp://project/123。

注册协议

1// src/main/system/protocol.ts
2import { app, BrowserWindow } from 'electron';
3
4const PROTOCOL = 'myapp';
5
6if (process.defaultApp) {
7  if (process.argv.length >= 2) {
8    app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, [process.argv[1]]);
9  }
10} else {
11  app.setAsDefaultProtocolClient(PROTOCOL);
12}
13
14// macOS:通过 open-url 唤起
15app.on('open-url', (event, url) => {
16  event.preventDefault();
17  handleDeepLink(url);
18});
19
20// Windows/Linux:通过 argv 传入
21app.on('second-instance', (_event, argv) => {
22  const url = argv.find((arg) => arg.startsWith(`${PROTOCOL}://`));
23  if (url) handleDeepLink(url);
24});
25
26function handleDeepLink(url: string): void {
27  const parsed = new URL(url);
28  if (parsed.protocol !== `${PROTOCOL}:`) return;
29  // 路由到主窗口
30  const win = BrowserWindow.getAllWindows()[0];
31  win?.webContents.send('deep-link', parsed.pathname);
32}

注意事项:

  • 开发模式下(process.defaultApp)需要把可执行文件与入口脚本一起注册,否则协议指向 Electron 本身。
  • macOS 的协议声明还需要在 Info.plist 中配置 CFBundleURLTypes,打包工具通常会自动生成。
  • 深链接参数必须校验,不能直接拼进命令行或文件路径。

应用内协议

如果只是让页面加载本地资源,使用 protocol.handle:

1import { protocol, net } from 'electron';
2import path from 'node:path';
3import { pathToFileURL } from 'node:url';
4
5protocol.handle('app', (request) => {
6  const url = new URL(request.url);
7  const relative = path.normalize(url.pathname).replace(/^(\.\.[/\\])+/, '');
8  const filePath = path.join(__dirname, '../renderer', relative);
9  return net.fetch(pathToFileURL(filePath).toString());
10});

开机自启

1// src/main/system/login-item.ts
2import { app } from 'electron';
3
4export function setAutoLaunch(enabled: boolean): void {
5  app.setLoginItemSettings({
6    openAtLogin: enabled,
7    openAsHidden: true, // macOS:登录后隐藏启动
8    args: ['--autostart'],
9  });
10}
11
12export function wasLaunchedAtLogin(): boolean {
13  return process.argv.includes('--autostart');
14}

平台差异:

平台行为
macOS通过 Login Items 注册,openAsHidden 在较新系统上语义有变化
Windows写入注册表 Run 项,安装路径变化后需要重新设置
Linux需自行写入 .desktop 文件到 autostart 目录

电源与后台行为

1// src/main/system/power.ts
2import { powerMonitor, powerSaveBlocker, BrowserWindow } from 'electron';
3
4export function setupPowerWatchers(getWindow: () => BrowserWindow | null): void {
5  powerMonitor.on('suspend', () => {
6    getWindow()?.webContents.send('power:suspend');
7  });
8
9  powerMonitor.on('resume', () => {
10    getWindow()?.webContents.send('power:resume');
11  });
12
13  powerMonitor.on('on-battery', () => {
14    // 降低动画频率、暂停非关键任务
15  });
16
17  powerMonitor.on('on-ac', () => {
18    // 恢复正常策略
19  });
20}
21
22let blockerId: number | null = null;
23
24export function preventSleep(): void {
25  if (blockerId === null) {
26    blockerId = powerSaveBlocker.start('prevent-display-sleep');
27  }
28}
29
30export function allowSleep(): void {
31  if (blockerId !== null) {
32    powerSaveBlocker.stop(blockerId);
33    blockerId = null;
34  }
35}

典型场景:

  • 视频播放、演示模式时阻止息屏。
  • 休眠唤醒后重新建立网络连接、刷新数据。
  • 电池模式下降低后台轮询频率。

自动更新

Electron 的自动更新有两套常见方案:

方案依赖平台适用
内置 autoUpdaterSquirrel(Windows)/ Squirrel.MacWindows、macOS简单场景,自建更新源
electron-updaterelectron-builder 生态Windows、macOS、Linux(部分)通用 provider、差分包、灰度

更新流程

使用electron-updater

1// src/main/system/updater.ts
2import { autoUpdater } from 'electron-updater';
3import { BrowserWindow } from 'electron';
4
5export function setupUpdater(getWindow: () => BrowserWindow | null): void {
6  autoUpdater.autoDownload = false;
7  autoUpdater.autoInstallOnAppQuit = true;
8
9  autoUpdater.on('update-available', (info) => {
10    getWindow()?.webContents.send('update:available', info.version);
11  });
12
13  autoUpdater.on('download-progress', (progress) => {
14    getWindow()?.webContents.send('update:progress', progress.percent);
15  });
16
17  autoUpdater.on('update-downloaded', () => {
18    getWindow()?.webContents.send('update:ready');
19  });
20
21  autoUpdater.on('error', (err) => {
22    console.error('update error', err);
23  });
24
25  void autoUpdater.checkForUpdates();
26}
27
28export function downloadUpdate(): Promise<void> {
29  return autoUpdater.downloadUpdate().then(() => undefined);
30}
31
32export function quitAndInstall(): void {
33  autoUpdater.quitAndInstall();
34}

更新策略

  1. 分渠道:stable/beta 分开配置更新源。
  2. 灰度:服务端按用户 ID 哈希返回不同版本,逐步放量。
  3. 强制更新:安全漏洞或协议不兼容时,提示不可跳过。
  4. 回滚:保留上一个可用版本,服务端能回退版本号。
  5. 签名校验:更新包必须签名,客户端验证后再安装。

系统集成排错

现象常见原因
Windows 通知不显示未设置 AppUserModelId、应用未正确安装
协议唤起无效未注册成功、开发模式注册路径错误、Info.plist 缺失
开机自启失效安装路径变化、系统权限限制、Linux 未写 desktop 文件
更新下载失败证书、代理、更新源地址、CSP/网络策略
托盘图标模糊未提供高分辨率图或未使用 Template 图
全局快捷键无效被其他应用占用、注册时机过早

本章小结

  • 菜单、托盘、通知、快捷键、文件对话框是桌面应用的基础设施,都要在主进程实现。
  • 平台差异集中在 macOS 应用菜单、Windows AppUserModelId、Linux 桌面环境。
  • 自定义协议要同时处理 macOS open-url 与 Windows second-instance。
  • 自动更新要覆盖检查、下载、安装、灰度、回滚与签名校验。
  • 所有系统能力都要考虑失败降级,不能阻塞应用启动。

参考资料