跳到主要内容

Electron 速查表

本速查表提供 Electron 开发中常用的 API 和代码片段,方便快速查阅。

主进程常用模块

app 模块

const { app } = require('electron')

app.whenReady().then(() => {})

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})

app.on('activate', () => {})

app.quit()
app.exit(0)
app.relaunch()

app.getPath('userData')
app.getPath('documents')
app.getPath('downloads')
app.getPath('desktop')

app.getVersion()
app.getName()
app.isPackaged

BrowserWindow

const { BrowserWindow } = require('electron')

const win = new BrowserWindow({
width: 800,
height: 600,
minWidth: 400,
minHeight: 300,
show: false,
frame: true,
transparent: false,
resizable: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
webSecurity: true
}
})

win.loadFile('index.html')
win.loadURL('https://example.com')

win.show()
win.hide()
win.close()
win.destroy()

win.minimize()
win.maximize()
win.unmaximize()
win.restore()
win.setFullScreen(true)

win.setSize(800, 600)
win.getSize()
win.setPosition(100, 100)
win.getPosition()
win.center()

win.webContents.openDevTools()
win.webContents.send('channel', data)

BrowserWindow.getAllWindows()
BrowserWindow.getFocusedWindow()
BrowserWindow.fromId(id)

ipcMain

const { ipcMain } = require('electron')

ipcMain.on('channel', (event, data) => {
event.reply('reply-channel', response)
event.sender.send('reply-channel', response)
})

ipcMain.handle('channel', async (event, data) => {
return result
})

ipcMain.removeAllListeners('channel')

dialog

const { dialog } = require('electron')

const result = await dialog.showOpenDialog({
title: '选择文件',
filters: [{ name: '文本', extensions: ['txt'] }],
properties: ['openFile', 'multiSelections']
})

const result = await dialog.showSaveDialog({
title: '保存文件',
defaultPath: 'untitled.txt',
filters: [{ name: '文本', extensions: ['txt'] }]
})

const result = await dialog.showMessageBox({
type: 'info',
title: '提示',
message: '操作完成',
buttons: ['确定', '取消']
})

dialog.showErrorBox('错误', '发生错误')
const { Menu } = require('electron')

const menu = Menu.buildFromTemplate([
{
label: '文件',
submenu: [
{ label: '新建', accelerator: 'CmdOrCtrl+N', click: () => {} },
{ type: 'separator' },
{ role: 'quit', label: '退出' }
]
},
{
label: '编辑',
submenu: [
{ role: 'undo', label: '撤销' },
{ role: 'redo', label: '重做' },
{ type: 'separator' },
{ role: 'cut', label: '剪切' },
{ role: 'copy', label: '复制' },
{ role: 'paste', label: '粘贴' }
]
}
])

Menu.setApplicationMenu(menu)

const contextMenu = Menu.buildFromTemplate([...])
contextMenu.popup()

Tray

const { Tray, Menu } = require('electron')

const tray = new Tray('icon.png')

tray.setToolTip('我的应用')
tray.setContextMenu(Menu.buildFromTemplate([...]))

tray.on('click', () => {})
tray.on('right-click', () => {})

shell

const { shell } = require('electron')

shell.openExternal('https://example.com')
shell.openPath('/path/to/file')
shell.showItemInFolder('/path/to/file')
shell.trashItem('/path/to/file')

clipboard

const { clipboard } = require('electron')

clipboard.writeText('text')
clipboard.readText()
clipboard.writeHTML('<b>html</b>')
clipboard.readHTML()
clipboard.clear()
clipboard.has('text')

Notification

const { Notification } = require('electron')

if (Notification.isSupported()) {
const notification = new Notification({
title: '标题',
body: '内容'
})
notification.on('click', () => {})
notification.show()
}

预加载脚本

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('electronAPI', {
send: (channel, data) => {
const validChannels = ['channel1', 'channel2']
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data)
}
},
invoke: (channel, data) => {
const validChannels = ['channel1', 'channel2']
if (validChannels.includes(channel)) {
return ipcRenderer.invoke(channel, data)
}
return Promise.reject(new Error('Invalid channel'))
},
on: (channel, callback) => {
const validChannels = ['channel1', 'channel2']
if (validChannels.includes(channel)) {
ipcRenderer.on(channel, (event, ...args) => callback(...args))
}
}
})

渲染进程

// 发送消息
window.electronAPI.send('channel', data)

// 调用并等待结果
const result = await window.electronAPI.invoke('channel', data)

// 监听消息
window.electronAPI.on('channel', (data) => {
console.log(data)
})

安全配置

const mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
allowRunningInsecureContent: false,
experimentalFeatures: false,
preload: path.join(__dirname, 'preload.js')
}
})

常用事件

app 事件

事件说明
ready应用初始化完成
window-all-closed所有窗口关闭
before-quit应用即将退出
will-quit应用将要退出
quit应用已退出
activate应用被激活

BrowserWindow 事件

事件说明
close窗口即将关闭
closed窗口已关闭
ready-to-show窗口准备好显示
maximize窗口最大化
unmaximize取消最大化
minimize窗口最小化
restore窗口恢复
resize窗口大小改变
move窗口移动
focus窗口获得焦点
blur窗口失去焦点

webContents 事件

事件说明
did-start-loading开始加载
did-finish-load加载完成
did-fail-load加载失败
context-menu右键菜单
will-navigate即将导航

常用路径

app.getPath('home')
app.getPath('appData')
app.getPath('userData')
app.getPath('sessionData')
app.getPath('temp')
app.getPath('exe')
app.getPath('desktop')
app.getPath('documents')
app.getPath('downloads')
app.getPath('music')
app.getPath('pictures')
app.getPath('videos')
app.getPath('logs')

打包配置

{
"build": {
"appId": "com.example.app",
"productName": "应用名称",
"directories": {
"output": "dist"
},
"files": [
"**/*",
"!**/node_modules/.bin"
],
"win": {
"target": "nsis",
"icon": "build/icon.ico"
},
"mac": {
"target": "dmg",
"icon": "build/icon.icns"
},
"linux": {
"target": "AppImage",
"icon": "build/icon.png"
}
}
}

常用命令

# 安装 Electron
npm install electron --save-dev

# 运行应用
npm start

# 打包应用
npx electron-builder

# 打包特定平台
npx electron-builder --win
npx electron-builder --mac
npx electron-builder --linux

# 重新编译原生模块
npx electron-rebuild

process.versions

process.versions.electron
process.versions.node
process.versions.chrome
process.versions.v8
process.versions.modules

平台判断

process.platform === 'win32'
process.platform === 'darwin'
process.platform === 'linux'

process.arch === 'x64'
process.arch === 'arm64'