Electron API 速查与配置模板

按用途分类的常用 API 索引,以及可直接复制的配置片段。

Intermediate
Key Points把最常用的 API 按「主进程 / 渲染进程 / 通用」分类列出来,配一份可直接用的窗口与打包配置。

主进程 API

ModuleKey members
appwhenReady、quit、getPath、setLoginItemSettings、requestSingleInstanceLock
BrowserWindowloadFile、loadURL、webContents、setMenu
MenubuildFromTemplate、setApplicationMenu、popup
TraysetToolTip、setContextMenu、on('click')
dialogshowOpenDialog、showSaveDialog、showMessageBox
NotificationisSupported、show
shellopenExternal、openPath、showItemInFolder
globalShortcutregister、unregisterAll
ipcMainhandle、on、removeHandler
sessiondefaultSession、setProxy、webRequest
nativeThemeshouldUseDarkColors、themeSource
clipboardreadText、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.

Friends & Partners