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 }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/electron-native-lab/explore-native.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-native.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a1081.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1089.zip