Electron 简介
Electron 是一个使用 JavaScript、HTML 和 CSS 构建跨平台桌面应用程序的框架。它将 Chromium 和 Node.js 合并到同一个运行时环境中,使开发者能够使用 Web 技术构建桌面应用。
主进程 - Main Process
- 可以使用和系统对接的 Electron API - 创建菜单,上次文件等等
- 可以创建多个 渲染进程 Renderer Process
- 全面支持 Node.js
- 只有一个主进程,作为整个程序的入口点
- 负责创建和管理应用窗口
- 处理系统级事件(如应用启动、退出等)
- 管理应用生命周期
- 可以访问所有 Node.js API
渲染进程 - Renderer Process
- 可以有多个,每个对应一个窗口
- 每个都是一个单独的进程
- 全面支持 Node.js 和 DOM API
- 可以使用一部分 Electron 提供的 API
- 负责渲染用户界面
- 处理用户交互
- 可以访问部分 Node.js API(需要配置)
- 默认情况下运行在沙箱环境中
进程之间的通讯方式
Electron 使用 IPC (进程间通信) 在进程之间进行通讯,和 Chromium 完全一致。
IPC 通信方式
ipcMain (主进程)
- 监听来自渲染进程的消息
- 发送消息到渲染进程
- 处理渲染进程的请求
ipcRenderer (渲染进程)
- 发送消息到主进程
- 监听来自主进程的消息
- 请求主进程执行操作
示例代码
主进程 (main.js):
const { ipcMain } = require('electron')
// 监听来自渲染进程的消息
ipcMain.on('message-to-main', (event, arg) => {
console.log(arg) // 打印 "Hello from renderer"
// 回复消息给渲染进程
event.reply('message-from-main', 'Hello from main process')
})
渲染进程 (renderer.js):
const { ipcRenderer } = require('electron')
// 发送消息到主进程
ipcRenderer.send('message-to-main', 'Hello from renderer')
// 监听来自主进程的回复
ipcRenderer.on('message-from-main', (event, arg) => {
console.log(arg) // 打印 "Hello from main process"
})
实践
项目设置
- 初始化项目
npm init
npm install electron --save-dev
- 配置开发环境
- 安装nodemon
npm install nodemon --save-dev
- 修改package.json
"start": "nodemon --watch main.js --exec 'electron .'"
主进程配置
main.js : 创建窗口 - BrowserWindow
const {app, BrowserWindow} = require('electron')
app.on('ready', () => {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true
}
})
mainWindow.loadFile('./index.html')
// 打开开发者工具
mainWindow.webContents.openDevTools()
})
// 处理窗口关闭事件
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
安全最佳实践
上下文隔离
- 启用
contextIsolation: true
- 使用
preload
脚本安全地暴露 API
- 启用
沙箱模式
- 默认启用沙箱模式
- 限制渲染进程的权限
内容安全策略 (CSP)
- 设置适当的 CSP 头
- 限制资源加载来源
进程间通信安全
- 验证所有 IPC 消息
- 限制 IPC 通道的使用
调试技巧
主进程调试
- 使用
--inspect
参数启动应用 - 在 Chrome DevTools 中调试
- 使用
渲染进程调试
- 使用
webContents.openDevTools()
- 使用 Chrome DevTools 进行调试
- 使用
打包和分发
- 使用 electron-builder
npm install electron-builder --save-dev
- 配置 package.json
{
"build": {
"appId": "com.example.app",
"mac": {
"category": "public.app-category.utilities"
},
"win": {
"target": "nsis"
},
"linux": {
"target": "AppImage"
}
}
}
- 构建命令
electron-builder build
性能优化
内存管理
- 及时释放不需要的资源
- 使用
webContents.clearCache()
启动优化
- 使用
app.commandLine.appendSwitch('disable-gpu')
- 延迟加载非关键模块
- 使用
渲染进程优化
- 使用
requestIdleCallback
- 避免阻塞主线程
- 使用
常见问题解决
白屏问题
- 检查文件路径
- 确认 webPreferences 配置
进程通信失败
- 检查 IPC 通道名称
- 确认消息格式
打包问题
- 检查依赖项
- 确认资源路径