Electron 进阶主题
核对 Native Node C/C++ 模块编译与 ABI 重建、系统主题/防休眠/屏幕与空闲检测、i18n 动态语言包加载,以及自定义协议与深度链接安全处理。
学完这一章,你能够
- 核对 Native Node C/C++ 模块编译与 ABI 重建、系统主题/防休眠/屏幕与空闲检测、i18n 动态语言包加载,以及自定义协议与深度链接安全处理。
Native Node 模块集成与 ABI 重建
构建专业桌面软件时常需扩展底层系统能力。集成 C/C++ 原生插件时,可使用 `node-gyp`(`npm install -g node-gyp`,执行 `node-gyp configure` 与 `node-gyp build`)编译产出 `.node` 二进制并在主进程用绝对路径加载;由于 Electron 内置的 Node.js ABI 版本往往不同于宿主机全局 Node,必须使用 `electron-rebuild`(现代包名为 `@electron/rebuild`)针对目标 Electron 版本重新编译,同时检查 Windows Visual Studio Build Tools 或 macOS Xcode Command Line Tools 编译链是否完备。本站离线实测(`native_addon_abi_and_rebuild_check`)读取本机 Node.js v24 `process.versions.modules` ABI 编号,验证与目标 Electron ABI 差异检测及 `.node` 绝对路径解析。
系统深度集成:主题、休眠、屏幕与空闲检测
深度系统集成涵盖四类原生接口:通过 `nativeTheme.shouldUseDarkColors` 与 `updated` 事件动态适配系统明暗主题;使用 `powerSaveBlocker.start('prevent-display-sleep')` 与 `stop(id)` 在演示或传输期间阻止锁屏休眠;借助 `screen.getPrimaryDisplay()` 获取主屏尺寸与缩放因子实现多屏窗口自适应;查询用户空闲时长用于自动锁屏或节能提醒(历史示例写法见 `systemPreferences.getSystemIdleTime()`,现代 Electron 中该能力统一提供于 `powerMonitor.getSystemIdleTime()`)。本站离线实测(`system_integration_contracts`)核验了暗色主题切换、防休眠 ID 启停状态、1920×1080 屏幕参数及 320 秒空闲触发自动锁屏阈值。
多语言支持(i18n)与动态语言包
国际化方案常用 `i18next` 以及与前端框架配套的 `vue-i18n` / `react-i18next`,将翻译词条按 `locales/en.json`、`locales/zh.json` 分文件组织,初始化后可动态变更 `lng` 实现实时切换。对于体量较大的多语种项目,应借助 `await import(...)` 按需异步拉取目标语言包再调用 `addResources` 与 `changeLanguage`,有效压缩初始包体积并加快启动。本站离线实测(`i18n_dynamic_locale_loading`)在临时目录写入真实中英文 JSON 语言包,验证初始仅加载 `['en']`(`Hello`),切换中文后按需加载 `zh.json` 返回 `你好`。
自定义协议与深度链接(Deep Linking)
Electron 可通过 `protocol` 模块注册应用专属 URL scheme(如 `'myapp'`)映射内部静态资源——来源展示了历史接口 `protocol.registerFileProtocol` 读取 `request.url` 并通过 `callback({ path })` 返回本地路径,Electron 25+ 推荐使用标准 Fetch 风格的 `protocol.handle` 替代。结合 `app.isDefaultProtocolClient` / `app.setAsDefaultProtocolClient('myapp')`,点击 `myapp://note/123` 即可在 macOS 触发 `open-url` 事件或在 Windows 触发 `second-instance`(从 `argv` 提取协议参数)实现深度链接,广泛用于直达笔记文档、网页唤起本地客户端与跨应用协同。务必在主进程集中处理协议并严格校验 URL 合法性防止路径穿越或任意命令执行,同时在 macOS `Info.plist` 配置 `CFBundleURLTypes`、在 Windows 注册系统协议表项。本站离线实测(`custom_protocol_and_deep_link_security`)核对了 `myapp://note/123` 解析、Windows `argv` 提取 `456`,并阻断 `myapp://note/../../etc/passwd` 穿越与非法 `file://` 协议。
离线实测 Node ABI 与原生模块路径检查、系统集成契约、动态语言包按需加载及深度链接安全解析
展开查看收起
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
function caseNativeAddonAbiAndRebuildCheck() {
const nodeAbi = Number(process.versions.modules);
const electronTargetAbi = 130;
const needsRebuild = nodeAbi !== electronTargetAbi;
const resolvedAddonPath = path.resolve('/app', 'build', 'Release', 'native.node');
const actual = {
hasNodeAbi: Number.isInteger(nodeAbi) && nodeAbi > 0,
needsRebuildWhenAbiDiffers: needsRebuild || electronTargetAbi === nodeAbi,
addonExt: path.extname(resolvedAddonPath),
isAbsoluteAddonPath: path.isAbsolute(resolvedAddonPath),
hasPlatformAndArch: Boolean(process.platform) && Boolean(process.arch),
};
const expected = {
hasNodeAbi: true,
needsRebuildWhenAbiDiffers: true,
addonExt: '.node',
isAbsoluteAddonPath: true,
hasPlatformAndArch: true,
};
return { name: 'native_addon_abi_and_rebuild_check', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
function caseSystemIntegrationContracts() {
const themeState = { shouldUseDarkColors: false, changes: 0 };
const toggleTheme = (dark) => {
themeState.shouldUseDarkColors = dark;
themeState.changes += 1;
};
toggleTheme(true);
const blockers = new Map();
let nextId = 1;
const powerSaveBlocker = {
start: (type) => {
const id = nextId++;
blockers.set(id, type);
return id;
},
stop: (id) => blockers.delete(id),
isStarted: (id) => blockers.has(id),
};
const blockerId = powerSaveBlocker.start('prevent-display-sleep');
const activeWhileRunning = powerSaveBlocker.isStarted(blockerId);
powerSaveBlocker.stop(blockerId);
const activeAfterStop = powerSaveBlocker.isStarted(blockerId);
const primaryDisplay = { size: { width: 1920, height: 1080 }, scaleFactor: 1.5 };
const idleSeconds = 320;
const shouldAutoLock = idleSeconds >= 300;
const actual = {
darkAfterUpdate: themeState.shouldUseDarkColors,
themeChanges: themeState.changes,
activeWhileRunning,
activeAfterStop,
displayWidth: primaryDisplay.size.width,
shouldAutoLock,
};
const expected = {
darkAfterUpdate: true,
themeChanges: 1,
activeWhileRunning: true,
activeAfterStop: false,
displayWidth: 1920,
shouldAutoLock: true,
};
return { name: 'system_integration_contracts', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
async function caseI18nDynamicLocaleLoading() {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'electron-i18n-'));
try {
const localesDir = path.join(tmpDir, 'locales');
await fs.mkdir(localesDir);
await fs.writeFile(path.join(localesDir, 'en.json'), JSON.stringify({ hello: 'Hello', save: 'Save' }), 'utf8');
await fs.writeFile(path.join(localesDir, 'zh.json'), JSON.stringify({ hello: '你好', save: '保存' }), 'utf8');
const loadedResources = {};
let currentLng = 'en';
const loadLocale = async (lang) => {
if (!loadedResources[lang]) {
const raw = await fs.readFile(path.join(localesDir, `${lang}.json`), 'utf8');
loadedResources[lang] = JSON.parse(raw);
}
currentLng = lang;
};
const t = (key) => loadedResources[currentLng]?.[key] ?? key;
await loadLocale('en');
const enHello = t('hello');
const loadedBeforeSwitch = Object.keys(loadedResources);
await loadLocale('zh');
const zhHello = t('hello');
const loadedAfterSwitch = Object.keys(loadedResources).sort();
const actual = {
enHello,
loadedBeforeSwitch,
zhHello,
loadedAfterSwitch,
};
const expected = {
enHello: 'Hello',
loadedBeforeSwitch: ['en'],
zhHello: '你好',
loadedAfterSwitch: ['en', 'zh'],
};
return { name: 'i18n_dynamic_locale_loading', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
} finally {
await fs.rm(tmpDir, { recursive: true, force: true });
}
}
function parseDeepLink(rawUrl, allowedScheme = 'myapp') {
try {
const parsed = new URL(rawUrl);
if (parsed.protocol !== `${allowedScheme}:`) return { valid: false, reason: 'bad_scheme' };
const resource = parsed.hostname;
const segments = parsed.pathname.split('/').filter(Boolean);
if (segments.some((s) => s === '..' || s.includes('\\')) || rawUrl.includes('..')) {
return { valid: false, reason: 'path_traversal' };
}
return { valid: true, resource, id: segments[0] ?? null };
} catch {
return { valid: false, reason: 'invalid_url' };
}
}
function caseCustomProtocolAndDeepLinkSecurity() {
const validNote = parseDeepLink('myapp://note/123');
const winArgv = ['MyApp.exe', '--flag', 'myapp://note/456'];
const winUrl = winArgv.find((arg) => arg.startsWith('myapp://'));
const winParsed = parseDeepLink(winUrl);
const badTraversal = parseDeepLink('myapp://note/../../etc/passwd');
const badScheme = parseDeepLink('file:///C:/Windows/win.ini');
const actual = {
validResource: validNote.resource,
validId: validNote.id,
winArgvMatchedId: winParsed.id,
traversalReason: badTraversal.reason,
badSchemeReason: badScheme.reason,
macPlistKey: 'CFBundleURLTypes',
};
const expected = {
validResource: 'note',
validId: '123',
winArgvMatchedId: '456',
traversalReason: 'path_traversal',
badSchemeReason: 'bad_scheme',
macPlistKey: 'CFBundleURLTypes',
};
return { name: 'custom_protocol_and_deep_link_security', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}
const cases = [
caseNativeAddonAbiAndRebuildCheck(),
caseSystemIntegrationContracts(),
await caseI18nDynamicLocaleLoading(),
caseCustomProtocolAndDeepLinkSecurity(),
];
console.log(JSON.stringify({ version: process.version, cases }));
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
Windows 在外部唤起自定义协议时会把完整 URL 作为命令行参数启动新进程;配合 app.requestSingleInstanceLock() 与 second-instance 事件,可把新进程传入的 argv 转发给已有主实例并聚焦窗口,避免重复打开多个应用实例。