Electron 原生功能集成(2025 年 12 月最新)
Electron 通过主进程 API 提供了丰富的操作系统原生功能集成,让你的 Web 应用看起来和感觉像真正的桌面原生应用。这些功能包括菜单、系统托盘(Tray)、对话框(Dialog)和通知(Notification),全部跨平台支持 Windows、macOS 和 Linux(部分功能有平台差异)。
这些 API 都在主进程中使用(不能在渲染进程直接调用,除非通过 IPC 桥接)。
1. 原生菜单(Menu)
Electron 支持应用菜单栏(顶部菜单)和上下文菜单(右键菜单)。
- 应用菜单:macOS 上是全局菜单栏,Windows/Linux 上是每个窗口的菜单栏。
示例代码(main.js):
const { app, Menu } = require('electron');
const template = [
{
label: '文件',
submenu: [
{ role: 'quit', label: '退出' }
]
},
{
label: '编辑',
submenu: [
{ role: 'copy', label: '复制' },
{ role: 'paste', label: '粘贴' }
]
}
];
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu); // 设置应用菜单
- 上下文菜单:右键弹出。
const { Menu } = require('electron');
const contextMenu = Menu.buildFromTemplate([
{ label: '复制', role: 'copy' },
{ label: '粘贴', role: 'paste' }
]);
contextMenu.popup({ window: mainWindow }); // 在指定窗口弹出
平台差异:macOS 支持更多 role(如 about、hide),Windows 用 & 定义快捷键(如 &File → Alt+F)。
2. 系统托盘(Tray)
在任务栏/通知区添加图标,常用于后台运行应用(如最小化到托盘)。
示例代码:
const { app, Tray, Menu, nativeImage } = require('electron');
let tray = null;
app.whenReady().then(() => {
const icon = nativeImage.createFromPath('path/to/icon.png'); // 支持 PNG/ICO
tray = new Tray(icon);
tray.setToolTip('我的 Electron 应用');
const contextMenu = Menu.buildFromTemplate([
{ label: '显示', click: () => mainWindow.show() },
{ label: '退出', role: 'quit' }
]);
tray.setContextMenu(contextMenu);
tray.on('click', () => mainWindow.show()); // 点击托盘图标显示窗口
});
平台差异:
- macOS:支持模板图像(黑白图标)、标题显示。
- Windows:推荐 ICO 格式,支持气球通知。
- Linux:位置取决于桌面环境。
3. 原生对话框(Dialog)
包括消息框、打开/保存文件对话框。
示例代码(异步推荐):
const { dialog } = require('electron');
// 消息框
dialog.showMessageBox(mainWindow, {
type: 'info',
title: '提示',
message: '这是一个消息',
buttons: ['确定', '取消']
}).then(result => {
console.log(result.response); // 点击的按钮索引
});
// 打开文件
dialog.showOpenDialog(mainWindow, {
properties: ['openFile', 'multiSelections'],
filters: [{ name: 'Images', extensions: ['jpg', 'png'] }]
}).then(result => {
if (!result.canceled) console.log(result.filePaths);
});
// 保存文件
dialog.showSaveDialog(mainWindow, {
defaultPath: 'filename.txt'
}).then(result => {
if (!result.canceled) console.log(result.filePath);
});
支持同步版本(如 showOpenDialogSync),但异步更友好(不阻塞进程)。
4. 系统通知(Notification)
显示桌面通知,支持标题、正文、图标、声音等。
示例代码:
const { Notification } = require('electron');
if (Notification.isSupported()) {
new Notification({
title: '新消息',
body: '你有一条新通知!',
icon: 'path/to/icon.png', // 可选
silent: false
}).show();
}
// 监听点击
notification.on('click', () => console.log('通知被点击'));
平台差异:macOS 支持回复按钮、动作;Windows 支持自定义模板;Linux 支持 urgency 级别。
这些原生功能让 Electron 应用更专业、更集成系统。所有代码都在主进程执行,渲染进程需通过 IPC 调用。官方文档:https://www.electronjs.org/docs/latest/api
如果需要完整示例项目、某个功能的深入代码,或集成到现有应用的指导,随时告诉我~