Electron API 速查与配置模板
按用途分类的常用 API 索引,以及可直接复制的配置片段。
Key Points把最常用的 API 按「主进程 / 渲染进程 / 通用」分类列出来,配一份可直接用的窗口与打包配置。
主进程 API
| Module | Key members |
|---|---|
app | whenReady、quit、getPath、setLoginItemSettings、requestSingleInstanceLock |
BrowserWindow | loadFile、loadURL、webContents、setMenu |
Menu | buildFromTemplate、setApplicationMenu、popup |
Tray | setToolTip、setContextMenu、on('click') |
dialog | showOpenDialog、showSaveDialog、showMessageBox |
Notification | isSupported、show |
shell | openExternal、openPath、showItemInFolder |
globalShortcut | register、unregisterAll |
ipcMain | handle、on、removeHandler |
session | defaultSession、setProxy、webRequest |
nativeTheme | shouldUseDarkColors、themeSource |
clipboard | readText、writeText、readImage |
渲染进程可用的 API
JavaScript
// preload 里能拿到的(受 sandbox 限制)
const { contextBridge, ipcRenderer, webFrame } = require('electron');
// 页面里只能拿到 preload 暴露的东西
window.api.xxx();
// 少量浏览器自带能力
window.electron // 仅在 nodeIntegration 时存在,别用With sandbox: true the preload script can only use a small slice of require('electron') (contextBridge, ipcRenderer, webFrame) and cannot require('fs'). File work belongs in the main process.
窗口配置模板
JavaScript
const win = new BrowserWindow({
width: 1200, height: 800,
minWidth: 900, minHeight: 600,
show: false,
backgroundColor: '#0b1220',
titleBarStyle: 'default',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
webSecurity: true,
spellcheck: false
}
});
win.once('ready-to-show', () => win.show());打包配置模板
JSON
{
"appId": "com.example.app",
"productName": "App",
"directories": { "output": "release", "buildResources": "build" },
"files": ["main.js", "preload.js", "dist/**/*", "!**/*.map"],
"asar": true,
"asarUnpack": ["**/*.node"],
"win": { "target": ["nsis"], "icon": "build/icon.ico" },
"nsis": { "oneClick": false, "allowToChangeInstallationDirectory": true },
"mac": { "target": ["dmg"], "icon": "build/icon.icns",
"hardenedRuntime": true,
"entitlements": "build/entitlements.mac.plist" },
"linux": { "target": ["AppImage", "deb"], "category": "Utility" },
"publish": [{ "provider": "generic", "url": "https://dl.example.com/app/" }]
}IPC 命名约定
JavaScript
// 用「域:动作」的格式,一眼能看出属于哪块功能
'settings:load'
'settings:save'
'file:open'
'file:save'
'window:minimize'
'update:check'
// 主进程侧统一注册
['settings:load', 'settings:save', 'file:open'].forEach(...)In a project without conventions ipcMain.handle calls scatter everywhere, and registering a channel twice throws Attempted to register a second handler. A naming rule plus central registration avoids it.
This index is only a map; the official docs are authoritative for signatures. Electron removes APIs across major versions (
remote went away in v14), so check the version before copying old code.主进程 API
| 模块 | 主要成员 |
|---|---|
| app | whenReady、quit、getPath、setLoginItemSettings、requestSingleInstanceLock |
| 窗口 | loadFile、loadURL、webContents、setMenu |
| 菜单 | buildFromTemplate、setApplicationMenu、popup |
| 托盘 | setToolTip、setContextMenu、on('click') |
| 对话框 | showOpenDialog、showSaveDialog、showMessageBox |
| 通知 | isSupported、show |
| 系统外壳 | openExternal、openPath、showItemInFolder |
| 全局快捷键 | register、unregisterAll |
| IPC | handle、on、removeHandler |
| 会话 | defaultSession、setProxy、webRequest |
| 主题 | shouldUseDarkColors、themeSource |
| 剪贴板 | readText、writeText、readImage |
渲染进程可用的 API
JavaScript
// preload 里能拿到的(受 sandbox 限制)
const { contextBridge, ipcRenderer, webFrame } = require('electron');
// 页面里只能拿到 preload 暴露的东西
window.api.xxx();
// 少量浏览器自带能力
window.electron // 仅在 nodeIntegration 时存在,别用开了 sandbox: true 之后,预加载脚本只能用 require('electron') 里的一小部分(contextBridge、ipcRenderer、webFrame),不能 require('fs')。文件操作必须在主进程做。
窗口配置模板
JavaScript
const win = new BrowserWindow({
width: 1200, height: 800,
minWidth: 900, minHeight: 600,
show: false,
backgroundColor: '#0b1220',
titleBarStyle: 'default',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
webSecurity: true,
spellcheck: false
}
});
win.once('ready-to-show', () => win.show());打包配置模板
JSON
{
"appId": "com.example.app",
"productName": "App",
"directories": { "output": "release", "buildResources": "build" },
"files": ["main.js", "preload.js", "dist/**/*", "!**/*.map"],
"asar": true,
"asarUnpack": ["**/*.node"],
"win": { "target": ["nsis"], "icon": "build/icon.ico" },
"nsis": { "oneClick": false, "allowToChangeInstallationDirectory": true },
"mac": { "target": ["dmg"], "icon": "build/icon.icns",
"hardenedRuntime": true,
"entitlements": "build/entitlements.mac.plist" },
"linux": { "target": ["AppImage", "deb"], "category": "Utility" },
"publish": [{ "provider": "generic", "url": "https://dl.example.com/app/" }]
}IPC 命名约定
JavaScript
// 用「域:动作」的格式,一眼能看出属于哪块功能
'settings:load'
'settings:save'
'file:open'
'file:save'
'window:minimize'
'update:check'
// 主进程侧统一注册
['settings:load', 'settings:save', 'file:open'].forEach(...)命名乱的项目里,ipcMain.handle 会散落在各处,同一个功能被注册两次还会抛 Attempted to register a second handler。约定加集中注册能省掉这类问题。
API 速查只是索引,具体签名以官方文档为准。Electron 大版本之间会移除 API(比如
remote 模块在 14 版被移除),照抄旧代码时先确认版本。