Electron 进程通信机制详解
1. 基础 IPC 通信
渲染进程 → 主进程 (单向)
主进程 (electron/main.js
):
javascript
ipcMain.on('renderer-to-main', (event, data) => {
console.log('收到渲染进程消息:', data)
})
渲染进程 (Vue 组件):
javascript
import { ipcRenderer } from 'electron'
function sendMessage() {
ipcRenderer.send('renderer-to-main', { type: 'greeting', content: 'Hello Main!' })
}
主进程 → 渲染进程 (单向)
主进程:
javascript
const sendToRenderer = () => {
const win = BrowserWindow.getFocusedWindow()
win.webContents.send('main-to-renderer', { time: new Date().toISOString() })
}
渲染进程:
javascript
import { onMounted, onUnmounted } from 'vue'
onMounted(() => {
ipcRenderer.on('main-to-renderer', handleMainMessage)
})
onUnmounted(() => {
ipcRenderer.off('main-to-renderer', handleMainMessage)
})
function handleMainMessage(event, data) {
console.log('收到主进程消息:', data)
}
2. 请求-响应模式 (双向通信)
使用 invoke/handle (推荐)
主进程:
javascript
ipcMain.handle('get-app-info', async () => {
return {
version: app.getVersion(),
platform: process.platform
}
})
渲染进程:
javascript
async function fetchAppInfo() {
const appInfo = await ipcRenderer.invoke('get-app-info')
console.log('应用信息:', appInfo)
}
使用 send/reply (传统方式)
主进程:
javascript
ipcMain.on('get-user-data', (event) => {
event.reply('user-data-response', {
username: 'admin',
role: 'superuser'
})
})
渲染进程:
javascript
function getUserData() {
ipcRenderer.send('get-user-data')
ipcRenderer.once('user-data-response', (event, data) => {
console.log('用户数据:', data)
})
}
3. 使用 contextBridge 的安全通信
创建 preload.js
:
javascript
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
// 单向发送
send: (channel, data) => ipcRenderer.send(channel, data),
// 双向通信
invoke: (channel, data) => ipcRenderer.invoke(channel, data),
// 接收消息
on: (channel, callback) => {
const subscription = (event, ...args) => callback(...args)
ipcRenderer.on(channel, subscription)
return () => ipcRenderer.removeListener(channel, subscription)
},
// 一次性接收
once: (channel, callback) => {
ipcRenderer.once(channel, (event, ...args) => callback(...args))
}
})
在 Vue 组件中使用:
javascript
// 发送消息
window.electronAPI.send('renderer-event', { payload: 'data' })
// 请求-响应
const result = await window.electronAPI.invoke('get-data')
// 监听消息
const cleanup = window.electronAPI.on('main-event', (data) => {
console.log('收到:', data)
})
// 组件卸载时清理
onUnmounted(() => cleanup())
事件监听与清理
1. 渲染进程中的事件管理
最佳实践示例:
javascript
import { onMounted, onUnmounted, ref } from 'vue'
export default {
setup() {
const messages = ref([])
let cleanupFunctions = []
const addMessage = (msg) => messages.value.push(msg)
onMounted(() => {
// 添加多个监听器
const cleanup1 = window.electronAPI.on('message-1', addMessage)
const cleanup2 = window.electronAPI.on('message-2', addMessage)
cleanupFunctions = [cleanup1, cleanup2]
})
onUnmounted(() => {
// 清理所有监听器
cleanupFunctions.forEach(fn => fn())
})
return { messages }
}
}
2. 主进程中的事件管理
主进程事件清理示例:
javascript
// 存储事件处理器引用
const handlers = {}
function registerHandler(channel, handler) {
// 如果已存在,先移除
if (handlers[channel]) {
ipcMain.removeListener(channel, handlers[channel])
}
// 添加新处理器
ipcMain.on(channel, handler)
handlers[channel] = handler
}
// 使用方式
registerHandler('channel-1', (event, data) => {
console.log('处理消息:', data)
})
// 应用退出时清理
app.on('will-quit', () => {
Object.keys(handlers).forEach(channel => {
ipcMain.removeListener(channel, handlers[channel])
})
})
高级通信模式
1. 多窗口通信
主进程作为中介:
javascript
// 主进程
const windows = new Set()
function broadcastMessage(channel, data) {
windows.forEach(win => {
if (!win.isDestroyed()) {
win.webContents.send(channel, data)
}
})
}
ipcMain.on('broadcast-message', (event, { channel, data }) => {
broadcastMessage(channel, data)
})
渲染进程:
javascript
// 发送广播
window.electronAPI.send('broadcast-message', {
channel: 'global-update',
data: { type: 'refresh' }
})
// 接收广播
window.electronAPI.on('global-update', (data) => {
console.log('收到广播:', data)
})
2. 使用 SharedArrayBuffer 共享内存
主进程:
javascript
const { SharedArrayBuffer } = require('electron')
ipcMain.handle('get-shared-buffer', () => {
const buffer = new SharedArrayBuffer(1024)
const view = new Uint8Array(buffer)
view[0] = 42
return buffer
})
渲染进程:
javascript
const buffer = await window.electronAPI.invoke('get-shared-buffer')
const view = new Uint8Array(buffer)
console.log('共享内存值:', view[0]) // 42
安全最佳实践
1. 安全的 contextBridge 暴露
javascript
contextBridge.exposeInMainWorld('electronAPI', {
// 只暴露必要的API
openFile: () => ipcRenderer.invoke('dialog:openFile'),
// 验证输入
saveData: (data) => {
if (typeof data !== 'object') throw new Error('Invalid data type')
return ipcRenderer.invoke('save-data', data)
},
// 限制可用的频道
on: (channel, callback) => {
const validChannels = ['data-update', 'status-change']
if (!validChannels.includes(channel)) return
ipcRenderer.on(channel, (event, ...args) => callback(...args))
}
})
2. 生产环境安全配置
javascript
new BrowserWindow({
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
sandbox: true,
webSecurity: true,
preload: path.join(__dirname, 'preload.js')
}
})
总结
-
IPC 通信模式:
- 单向通信:
send/on
- 双向通信:
invoke/handle
或send/reply
- 广播通信: 通过主进程转发
- 单向通信:
-
事件管理最佳实践:
- 始终在组件卸载时清理事件监听器
- 使用
once
或存储清理函数引用 - 主进程集中管理事件处理器
-
安全注意事项:
- 生产环境启用
contextIsolation
和sandbox
- 通过
contextBridge
限制暴露的 API - 验证所有 IPC 通信的输入数据
- 生产环境启用
-
高级技巧:
- 使用 SharedArrayBuffer 进行高效数据共享
- 实现多窗口间的通信
- 添加全面的错误处理