Electron 原生功能集成
系统涵盖 Electron 原生菜单、右键上下文菜单、系统对话框、系统托盘、桌面通知、全局快捷键及完整原生功能演示工程,并在 Node.js v24 中实测菜单快捷键解析、文件过滤、托盘拦截与热键冲突检测。
学完这一章,你能够
- 系统涵盖 Electron 原生菜单、右键上下文菜单、系统对话框、系统托盘、桌面通知、全局快捷键及完整原生功能演示工程,并在 Node.js v24 中实测菜单快捷键解析、文件过滤、托盘拦截与热键冲突检测。
菜单系统:应用菜单、右键菜单与快捷键
Electron 的核心竞争力之一是允许主进程直接调用系统级原生桌面交互模块,包括菜单、对话框、托盘、通知与全局快捷键。使用 `Menu.buildFromTemplate(template)` 与 `Menu.setApplicationMenu(menu)` 即可定制应用菜单栏(macOS 位于屏幕顶部,Windows/Linux 位于窗口顶部),菜单项常用属性包括标题 `label`、嵌套数组 `submenu`、快捷键 `accelerator`、预定义系统行为 `role`(如 `quit`、`undo`、`redo`、`cut`、`copy`、`paste`)及回调 `click`。
右键上下文菜单由渲染进程拦截 `contextmenu` 事件并调用 `e.preventDefault()` 后通过 Preload/IPC 通知主进程,再由主进程执行 `menu.popup()` 弹出;系统托盘菜单则将 `Menu` 实例绑定到 `tray.setContextMenu(contextMenu)`。定义菜单快捷键时优先采用 `CmdOrCtrl` 前缀(如 `CmdOrCtrl+S`),框架会自动在 macOS 映射为 `Cmd`、在 Windows/Linux 映射为 `Ctrl`,并与 `Alt+F4`、`Cmd+Q` 等平台原生按键习惯兼容(`menu_template_accelerator_and_context_menu` 实测校验了菜单回调、跨平台快捷键解析与右键 IPC 弹窗列表)。
系统对话框、系统托盘与桌面通知
`dialog` 模块封装了操作系统原生模态对话框:`dialog.showOpenDialog` 支持 `openFile`、`multiSelections` 与扩展名 `filters` 过滤并返回 `filePaths`;`dialog.showSaveDialog` 可指定 `defaultPath` 获取保存路径 `filePath`;`dialog.showMessageBox` 用于展示信息/确认弹窗,`dialog.showErrorBox` 则用于同步弹出错误提示(`dialog_contracts_open_save_message` 实测过滤 `txt`/`md` 从 4 个候选中精确选出 `['readme.md', 'notes.txt']`)。
借助 `Tray`(传入图标路径或 `nativeImage`)可将应用常驻系统通知区,配合 `setToolTip` 与 `setContextMenu` 提供后台恢复/退出入口;`tray.displayBalloon` 仅适用于 Windows 托盘气泡提醒,监听窗口 `close` 事件并调用 `event.preventDefault()` + `mainWindow.hide()` 即可实现关闭按钮最小化到托盘。跨平台消息提醒推荐使用 `Notification` 类,调用 `.show()` 展示并可监听 `click` 交互事件;该接口支持 Windows、macOS(需授予通知权限)与 Linux(通常依赖 `libnotify`)。上述托盘隐藏与通知点击流程已在 `tray_notification_and_minimize_to_tray` 中实测通过。
全局快捷键与原生模块汇总
`globalShortcut` 用于在应用未获焦点时依然响应系统级热键,必须在 `app.whenReady()` 之后调用 `globalShortcut.register('CmdOrCtrl+Shift+I', cb)` 注册,并在退出前按需注销。为避免覆盖其他程序热键,注册前可用 `globalShortcut.isRegistered(...)` 查重,必要时根据 `process.platform === 'darwin'` 分支选用 `Cmd+Shift+T` 或 `Ctrl+Shift+T`。五大原生模块职责对照见下方汇总表。
原生功能综合演示项目解析
综合演示项目包含 `package.json`、`main.js`、`preload.js` 与 `index.html`:编写 `package.json` 时切忌掺入 `//` 注释,否则 npm 解析会直接报 `EJSONPARSE` 错误(`global_shortcut_conflict_and_demo_manifest` 实测确认标准 `JSON.parse` 拒绝含注释 JSON 并抛出 `SyntaxError`)。主进程在 `app.whenReady()` 后依次初始化窗口(关闭即隐藏到托盘)、含“文件/工具”两组的顶部菜单、托盘菜单与 `CmdOrCtrl+Shift+I` 调试热键,并通过 `ipcMain.handle('show-dialog')` 响应前端按钮点击;工程落地时,若 `index.html` 需监听主进程推送的 `file-opened` 路径,应在 `preload.js` 中一并暴露 `fileOpened` 回调封装,使顶部菜单打开文件后能实时回显路径。执行 `npm install` 与 `npm start` 后即可体验完整原生菜单、对话框、通知、托盘与热键联动。
Electron 常用原生集成模块速览
| 功能 | 模块 | 典型用途 |
| 菜单 | Menu | 应用顶部菜单栏、页面右键菜单与托盘菜单 |
| 对话框 | dialog | 系统文件打开/保存选择器、消息确认与错误弹窗 |
| 托盘 | Tray | 应用后台常驻、状态提示与托盘菜单入口 |
| 通知 | Notification | 发送跨平台系统级进度与消息提醒 |
| 全局快捷键 | globalShortcut | 注册不受窗口焦点限制的系统级热键 |
在 Node.js v24 中实测应用/右键菜单、文件对话框过滤、最小化到托盘、通知与全局热键冲突检测
展开查看收起
import { EventEmitter } from 'node:events';
function makeCase(name, expected, actual) {
return {
name,
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
};
}
const cases = [];
// Case 1: Application menu template, accelerator resolution & context menu IPC
{
const actions = [];
const template = [
{
label: '文件',
submenu: [
{ label: '新建文件', accelerator: 'CmdOrCtrl+N', click: () => actions.push('new-file') },
{ label: '打开...', accelerator: 'CmdOrCtrl+O' },
{ type: 'separator' },
{ label: '退出', role: 'quit' },
],
},
{
label: '编辑',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
],
},
];
template[0].submenu[0].click();
const resolveAccelerator = (acc, platform) =>
acc.replace('CmdOrCtrl', platform === 'darwin' ? 'Cmd' : 'Ctrl');
const ipc = new EventEmitter();
let popupItems = [];
ipc.on('show-context-menu', () => {
popupItems = ['刷新', '复制', '粘贴'];
});
ipc.emit('show-context-menu');
const expected = {
topMenus: ['文件', '编辑'],
fileItemCount: 4,
editRoles: ['undo', 'redo', 'cut', 'copy', 'paste'],
clickedActions: ['new-file'],
saveShortcutDarwin: 'Cmd+S',
saveShortcutWin32: 'Ctrl+S',
contextPopupItems: ['刷新', '复制', '粘贴'],
};
const actual = {
topMenus: template.map((m) => m.label),
fileItemCount: template[0].submenu.length,
editRoles: template[1].submenu.filter((i) => i.role).map((i) => i.role),
clickedActions: actions,
saveShortcutDarwin: resolveAccelerator('CmdOrCtrl+S', 'darwin'),
saveShortcutWin32: resolveAccelerator('CmdOrCtrl+S', 'win32'),
contextPopupItems: popupItems,
};
cases.push(makeCase('menu_template_accelerator_and_context_menu', expected, actual));
}
// Case 2: System dialog contracts (open/save filters, message & error boxes)
{
const filterExtensions = new Set(['txt', 'md']);
const candidateFiles = ['readme.md', 'notes.txt', 'archive.zip', 'photo.png'];
const matchedFiles = candidateFiles.filter((name) =>
filterExtensions.has(name.split('.').pop()),
);
const openResult = { canceled: false, filePaths: matchedFiles };
const saveResult = { canceled: false, filePath: '新建文档.txt' };
const messageBox = { type: 'info', title: '提示', message: '操作已完成!', response: 0 };
const errorBox = { title: '错误', content: '文件保存失败,请重试。' };
const expected = {
matchedFiles: ['readme.md', 'notes.txt'],
saveDefaultPath: '新建文档.txt',
messageResponse: 0,
errorTitle: '错误',
};
const actual = {
matchedFiles: openResult.filePaths,
saveDefaultPath: saveResult.filePath,
messageResponse: messageBox.response,
errorTitle: errorBox.title,
};
cases.push(makeCase('dialog_contracts_open_save_message', expected, actual));
}
// Case 3: Tray menu, minimize-to-tray close guard & Notification events
{
const trayState = {
toolTip: '',
contextLabels: [],
balloonShown: null,
};
trayState.toolTip = 'Electron 原生功能演示';
trayState.contextLabels = ['显示窗口', '退出'];
trayState.balloonShown = { title: '新消息', content: '您有一条新通知' };
const win = new EventEmitter();
win.visible = true;
win.on('close', (event) => {
event.preventDefault();
win.visible = false;
});
let prevented = false;
win.emit('close', {
preventDefault() {
prevented = true;
},
});
const notif = new EventEmitter();
let clicked = false;
notif.on('click', () => {
clicked = true;
});
notif.emit('click');
const expected = {
trayToolTip: 'Electron 原生功能演示',
trayMenuLabels: ['显示窗口', '退出'],
balloonTitle: '新消息',
closePrevented: true,
windowHiddenToTray: true,
notificationClicked: true,
platformNotes: { darwin: 'notification-permission', linux: 'libnotify' },
};
const actual = {
trayToolTip: trayState.toolTip,
trayMenuLabels: trayState.contextLabels,
balloonTitle: trayState.balloonShown.title,
closePrevented: prevented,
windowHiddenToTray: !win.visible,
notificationClicked: clicked,
platformNotes: { darwin: 'notification-permission', linux: 'libnotify' },
};
cases.push(makeCase('tray_notification_and_minimize_to_tray', expected, actual));
}
// Case 4: Global shortcut conflict detection, platform branch & strict JSON check
{
const registered = new Map();
const globalShortcut = {
isRegistered: (acc) => registered.has(acc),
register(acc, cb) {
if (registered.has(acc)) return false;
registered.set(acc, cb);
return true;
},
};
let triggered = 0;
const firstReg = globalShortcut.register('CmdOrCtrl+Shift+I', () => {
triggered += 1;
});
const duplicateReg = globalShortcut.register('CmdOrCtrl+Shift+I', () => {});
const isReg = globalShortcut.isRegistered('CmdOrCtrl+Shift+I');
registered.get('CmdOrCtrl+Shift+I')();
const platformShortcut = (plat) => (plat === 'darwin' ? 'Cmd+Shift+T' : 'Ctrl+Shift+T');
let jsonCommentRejected = false;
try {
JSON.parse('{ "name": "demo" // comment\n }');
} catch (err) {
jsonCommentRejected = err instanceof SyntaxError;
}
const expected = {
firstReg: true,
duplicateReg: false,
isRegistered: true,
triggeredCount: 1,
darwinShortcut: 'Cmd+Shift+T',
win32Shortcut: 'Ctrl+Shift+T',
jsonCommentRejected: true,
};
const actual = {
firstReg,
duplicateReg,
isRegistered: isReg,
triggeredCount: triggered,
darwinShortcut: platformShortcut('darwin'),
win32Shortcut: platformShortcut('win32'),
jsonCommentRejected,
};
cases.push(makeCase('global_shortcut_conflict_and_demo_manifest', expected, actual));
}
console.log(JSON.stringify({ version: process.version, cases }));
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
CmdOrCtrl 会由 Electron 自动在 macOS 映射为 Command 键、在 Windows/Linux 映射为 Ctrl 键,无需手写两套菜单模板;实现最小化到托盘需在主进程监听 mainWindow 的 close 事件,先调用 event.preventDefault() 阻止默认销毁,再调用 mainWindow.hide() 隐藏窗口。