Electron API 速查与配置模板(2025 年最新版)
以下是 Electron 开发中最常用 API 的快速参考表,以及生产级项目推荐的标准配置模板(基于 Electron 33+,Chromium 128+)。
1. 核心模块速查表
| 模块 | 常见 API | 用途与示例 |
|---|---|---|
| app | app.whenReady()app.getPath(name)app.setLoginItemSettings()app.on('window-all-closed') | 应用生命周期、路径获取、开机启动 示例: app.getPath('userData') 获取配置目录 |
| BrowserWindow | new BrowserWindow(options)win.loadURL()win.webContents.openDevTools() | 创建窗口、加载内容、调试 |
| ipcMain | ipcMain.handle(channel, handler)ipcMain.on(channel, listener) | 主进程接收渲染进程消息(推荐 handle 用于异步) |
| ipcRenderer | ipcRenderer.invoke(channel, args)ipcRenderer.send(channel, args) | 渲染进程向主进程通信 |
| session | ses.cookies.get/setses.setPermissionRequestHandler()ses.fetch() | Cookie 管理、权限控制、自定义网络请求 |
| net | net.request()net.fetch() (Electron 25+) | 主进程 HTTP/HTTPS 请求(支持系统代理) |
| safeStorage | safeStorage.encryptString/decryptString() | 系统级加密(密钥链/Keychain) |
| nativeImage | nativeImage.createFromPath() | 系统托盘图标、任务栏图标 |
| Tray | new Tray(image)tray.setContextMenu() | 系统托盘 |
| Menu | Menu.setApplicationMenu()Menu.buildFromTemplate() | 应用菜单、右键菜单 |
| dialog | dialog.showOpenDialog()dialog.showMessageBox() | 文件选择、消息弹窗 |
| shell | shell.openExternal(url) | 安全打开外部链接 |
| powerMonitor | powerMonitor.on('suspend') | 系统休眠/唤醒监听 |
| autoUpdater | autoUpdater.checkForUpdates() | 自动更新(需配合 electron-updater) |
2. 生产级 BrowserWindow 配置模板
// main.js
const { app, BrowserWindow, session } = require('electron');
const path = require('path');
function createWindow() {
const win = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 800,
minHeight: 600,
show: false, // 先隐藏,ready-to-show 再显示(防白屏)
icon: path.join(__dirname, 'build/icon.ico'), // 跨平台图标
webPreferences: {
preload: path.join(__dirname, 'preload.js'), // 必须
contextIsolation: true, // 必开(默认 true)
nodeIntegration: false, // 必关
sandbox: true, // 强烈推荐(渲染进程沙盒)
webSecurity: true, // 必开
allowRunningInsecureContent: false,
experimentalFeatures: false,
// backgroundThrottling: false, // 若需后台保持活跃可关闭
},
backgroundColor: '#fff', // 与前端首屏颜色一致
titleBarStyle: 'default', // macOS: 'hiddenInset' 可自定义标题栏
trafficLightPosition: { x: 12, y: 12 }, // macOS 交通灯位置
});
// 生产环境加载打包后的文件,开发环境加载 Vite 服务器
if (process.env.NODE_ENV === 'development') {
win.loadURL('http://localhost:5173');
win.webContents.openDevTools({ mode: 'detach' });
} else {
win.loadFile(path.join(__dirname, 'dist/index.html'));
}
win.once('ready-to-show', () => win.show());
// 安全:阻止新窗口弹出,改为浏览器打开
win.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
// 安全:阻止导航到外部
win.webContents.on('will-navigate', (e, url) => {
if (!url.startsWith('file:') && !url.includes('localhost')) {
e.preventDefault();
shell.openExternal(url);
}
});
return win;
}
app.whenReady().then(() => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
3. 安全 preload.js 模板(contextBridge)
// preload.js
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
// 推荐:白名单渠道
invoke: (channel, ...args) => {
const validChannels = ['get-data', 'save-file', 'open-dialog'];
if (validChannels.includes(channel)) {
return ipcRenderer.invoke(channel, ...args);
}
throw new Error(`Invalid channel: ${channel}`);
},
on: (channel, listener) => {
const validChannels = ['update-available', 'download-progress'];
if (validChannels.includes(channel)) {
ipcRenderer.on(channel, listener);
}
},
removeAllListeners: (channel) => ipcRenderer.removeAllListeners(channel),
});
4. package.json 关键配置模板(electron-builder)
{
"build": {
"appId": "com.yourcompany.yourapp",
"productName": "YourApp",
"directories": {
"output": "dist-electron"
},
"files": [
"dist/**/*",
"main/**/*",
"preload.js"
],
"extraResources": [
{
"from": "resources/",
"to": "resources",
"filter": ["**/*"]
}
],
"win": {
"target": ["nsis", "portable"],
"icon": "build/icon.ico"
},
"mac": {
"target": ["dmg", "zip"],
"icon": "build/icon.icns",
"hardenedRuntime": true,
"gatekeeperAssess": false
},
"linux": {
"target": ["AppImage", "deb"],
"icon": "build/icons"
},
"publish": [
{
"provider": "github",
"owner": "yourname",
"repo": "yourapp"
}
]
}
}
这些模板已集成当前最佳实践(沙盒 + 上下文隔离 + Fuses + 安全 IPC)。直接复制到新项目中使用,几乎可直接用于生产。如果需要特定功能(如托盘、自动更新、原生菜单)的完整代码模板,告诉我,我可以继续补充!