进程间通信
进程间通信 (IPC) 是构建功能丰富的 Electron 桌面应用程序的关键部分。由于主进程和渲染进程在 Electron 的进程模型中具有不同的职责,IPC 是执行许多常见任务的唯一方法,例如从您的 UI 调用原生 API,或从原生菜单触发对您的 Web 内容的更改。
IPC 通道
在 Electron 中,进程通过使用 ipcMain 和 ipcRenderer 模块通过开发者定义的“通道”传递消息进行通信。这些通道是任意的(您可以随意命名它们)并且是双向的(您可以对两个模块使用相同的通道名称)。
在本指南中,我们将介绍一些基本的 IPC 模式,并提供具体的示例,您可以将其作为应用程序代码的参考。
理解上下文隔离的进程
在继续实现细节之前,您应该熟悉使用 preload 脚本 在上下文隔离的渲染进程中导入 Node.js 和 Electron 模块的概念。
模式 1:渲染进程到主进程(单向)
要从渲染进程向主进程发送单向 IPC 消息,您可以使用 ipcRenderer.send API 发送消息,然后由 ipcMain.on API 接收该消息。
您通常使用此模式从您的 Web 内容中调用主进程 API。我们将通过创建一个可以以编程方式更改其窗口标题的简单应用程序来演示此模式。
对于此演示,您需要将代码添加到您的主进程、渲染进程和 preload 脚本中。完整的代码如下,但我们将在下面的部分中分别解释每个文件。
- main.js
- preload.js
- index.html
- renderer.js
const { app, BrowserWindow, ipcMain } = require('electron/main')
const path = require('node:path')
function handleSetTitle (event, title) {
const webContents = event.sender
const win = BrowserWindow.fromWebContents(webContents)
win.setTitle(title)
}
function createWindow () {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
}
app.whenReady().then(() => {
ipcMain.on('set-title', handleSetTitle)
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
const { contextBridge, ipcRenderer } = require('electron/renderer')
contextBridge.exposeInMainWorld('electronAPI', {
setTitle: (title) => ipcRenderer.send('set-title', title)
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://mdn.org.cn/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Hello World!</title>
</head>
<body>
Title: <input id="title"/>
<button id="btn" type="button">Set</button>
<script src="./renderer.js"></script>
</body>
</html>
const setButton = document.getElementById('btn')
const titleInput = document.getElementById('title')
setButton.addEventListener('click', () => {
const title = titleInput.value
window.electronAPI.setTitle(title)
})
1. 使用 ipcMain.on 监听事件
在主进程中,使用 ipcMain.on API 在 set-title 通道上设置一个 IPC 监听器
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('node:path')
// ...
function handleSetTitle (event, title) {
const webContents = event.sender
const win = BrowserWindow.fromWebContents(webContents)
win.setTitle(title)
}
function createWindow () {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
}
app.whenReady().then(() => {
ipcMain.on('set-title', handleSetTitle)
createWindow()
})
// ...
上面的 handleSetTitle 回调函数有两个参数:一个 IpcMainEvent 结构和一个 title 字符串。每当消息通过 set-title 通道时,此函数将找到附加到消息发送者的 BrowserWindow 实例,并在其上使用 win.setTitle API。
确保您正在加载以下步骤的 index.html 和 preload.js 入口点!
2. 通过 preload 暴露 ipcRenderer.send
要发送到上述监听器的消息,您可以使用 ipcRenderer.send API。默认情况下,渲染进程没有 Node.js 或 Electron 模块的访问权限。作为应用程序开发者,您需要使用 contextBridge API 选择要从您的 preload 脚本中暴露哪些 API。
在您的 preload 脚本中,添加以下代码,它将在您的渲染进程中暴露一个全局 window.electronAPI 变量。
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
setTitle: (title) => ipcRenderer.send('set-title', title)
})
此时,您将能够在渲染进程中使用 window.electronAPI.setTitle() 函数。
出于安全原因,我们不会直接暴露整个 ipcRenderer.send API。请确保尽可能限制渲染器对 Electron API 的访问权限。
3. 构建渲染进程 UI
在我们的 BrowserWindow 加载的 HTML 文件中,添加一个基本的用户界面,包括一个文本输入框和一个按钮
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://mdn.org.cn/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Hello World!</title>
</head>
<body>
Title: <input id="title"/>
<button id="btn" type="button">Set</button>
<script src="./renderer.js"></script>
</body>
</html>
为了使这些元素具有交互性,我们将添加几行代码到导入的 renderer.js 文件中,利用从 preload 脚本暴露的 window.electronAPI 功能
const setButton = document.getElementById('btn')
const titleInput = document.getElementById('title')
setButton.addEventListener('click', () => {
const title = titleInput.value
window.electronAPI.setTitle(title)
})
此时,您的演示应该完全正常。尝试使用输入字段,看看您的 BrowserWindow 标题会发生什么!
模式 2:渲染进程到主进程(双向)
双向 IPC 的一个常见应用是从您的渲染进程代码调用主进程模块并等待结果。这可以通过使用 ipcRenderer.invoke 与 ipcMain.handle 配对来完成。
在下面的示例中,我们将从渲染进程打开一个原生文件对话框,并返回所选文件的路径。
对于此演示,您需要将代码添加到您的主进程、渲染进程和 preload 脚本中。完整的代码如下,但我们将在下面的部分中分别解释每个文件。
- main.js
- preload.js
- index.html
- renderer.js
const { app, BrowserWindow, ipcMain, dialog } = require('electron/main')
const path = require('node:path')
async function handleFileOpen () {
const { canceled, filePaths } = await dialog.showOpenDialog()
if (!canceled) {
return filePaths[0]
}
}
function createWindow () {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
}
app.whenReady().then(() => {
ipcMain.handle('dialog:openFile', handleFileOpen)
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
const { contextBridge, ipcRenderer } = require('electron/renderer')
contextBridge.exposeInMainWorld('electronAPI', {
openFile: () => ipcRenderer.invoke('dialog:openFile')
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://mdn.org.cn/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Dialog</title>
</head>
<body>
<button type="button" id="btn">Open a File</button>
File path: <strong id="filePath"></strong>
<script src='./renderer.js'></script>
</body>
</html>
const btn = document.getElementById('btn')
const filePathElement = document.getElementById('filePath')
btn.addEventListener('click', async () => {
const filePath = await window.electronAPI.openFile()
filePathElement.innerText = filePath
})
1. 使用 ipcMain.handle 监听事件
在主进程中,我们将创建一个 handleFileOpen() 函数,该函数调用 dialog.showOpenDialog 并返回用户选择的文件路径的值。每当从渲染进程通过 dialog:openFile 通道发送 ipcRender.invoke 消息时,都会使用此函数作为回调。然后,返回值将作为 Promise 返回给原始 invoke 调用。
通过 handle 在主进程中抛出的错误不会透明地传递,它们会被序列化,并且只有原始错误的 message 属性提供给渲染进程。有关详细信息,请参阅 #24427。
const { app, BrowserWindow, dialog, ipcMain } = require('electron')
const path = require('node:path')
// ...
async function handleFileOpen () {
const { canceled, filePaths } = await dialog.showOpenDialog({})
if (!canceled) {
return filePaths[0]
}
}
function createWindow () {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
}
app.whenReady().then(() => {
ipcMain.handle('dialog:openFile', handleFileOpen)
createWindow()
})
// ...
dialog: 前缀在 IPC 通道名称上没有对代码产生影响。它仅作为帮助提高代码可读性的命名空间。
确保您正在加载以下步骤的 index.html 和 preload.js 入口点!
2. 通过 preload 暴露 ipcRenderer.invoke
在 preload 脚本中,我们暴露一个单行 openFile 函数,该函数调用并返回 ipcRenderer.invoke('dialog:openFile') 的值。我们将使用此 API 在渲染器的用户界面中调用原生对话框。
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
openFile: () => ipcRenderer.invoke('dialog:openFile')
})
出于安全原因,我们不会直接暴露整个 ipcRenderer.invoke API。请确保尽可能限制渲染器对 Electron API 的访问权限。
3. 构建渲染进程 UI
最后,让我们构建加载到我们的 BrowserWindow 中的 HTML 文件。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://mdn.org.cn/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Dialog</title>
</head>
<body>
<button type="button" id="btn">Open a File</button>
File path: <strong id="filePath"></strong>
<script src='./renderer.js'></script>
</body>
</html>
UI 由一个 #btn 按钮元素组成,该元素将用于触发我们的 preload API,以及一个 #filePath 元素,该元素将用于显示所选文件的路径。使这些部分工作需要渲染进程脚本中的几行代码
const btn = document.getElementById('btn')
const filePathElement = document.getElementById('filePath')
btn.addEventListener('click', async () => {
const filePath = await window.electronAPI.openFile()
filePathElement.innerText = filePath
})
在上面的代码片段中,我们监听 #btn 按钮上的点击事件,并调用我们的 window.electronAPI.openFile() API 以激活原生打开文件对话框。然后,我们将所选的文件路径显示在 #filePath 元素中。
注意:遗留方法
ipcRenderer.invoke API 是在 Electron 7 中添加的,作为从渲染进程处理双向 IPC 的一种更友好的方式。但是,存在几种替代此 IPC 模式的方法。
我们建议尽可能使用 ipcRenderer.invoke。以下双向渲染器到主进程模式是为历史目的记录的。
对于以下示例,我们直接从 preload 脚本调用 ipcRenderer,以使代码示例更小。
使用 ipcRenderer.send
我们用于单向通信的 ipcRenderer.send API 也可以用于执行双向通信。这是在 Electron 7 之前进行异步双向 IPC 的推荐方法。
// You can also put expose this code to the renderer
// process with the `contextBridge` API
const { ipcRenderer } = require('electron')
ipcRenderer.on('asynchronous-reply', (_event, arg) => {
console.log(arg) // prints "pong" in the DevTools console
})
ipcRenderer.send('asynchronous-message', 'ping')
ipcMain.on('asynchronous-message', (event, arg) => {
console.log(arg) // prints "ping" in the Node console
// works like `send`, but returning a message back
// to the renderer that sent the original message
event.reply('asynchronous-reply', 'pong')
})
此方法有一些缺点
- 您需要在渲染进程中设置第二个
ipcRenderer.on监听器来处理响应。使用invoke,您可以将响应值作为 Promise 返回给原始 API 调用。 - 没有明显的方法可以将
asynchronous-reply消息与原始asynchronous-message消息配对。如果您通过这些通道来回发送非常频繁的消息,您需要添加额外的应用程序代码来单独跟踪每个调用和响应。
使用 ipcRenderer.sendSync
ipcRenderer.sendSync API 将消息发送到主进程并同步等待响应。
const { ipcMain } = require('electron')
ipcMain.on('synchronous-message', (event, arg) => {
console.log(arg) // prints "ping" in the Node console
event.returnValue = 'pong'
})
// You can also put expose this code to the renderer
// process with the `contextBridge` API
const { ipcRenderer } = require('electron')
const result = ipcRenderer.sendSync('synchronous-message', 'ping')
console.log(result) // prints "pong" in the DevTools console
此代码的结构与 invoke 模型非常相似,但我们建议出于性能原因避免使用此 API。 其同步特性意味着它会阻塞渲染进程,直到收到回复为止。
模式 3:主进程到渲染器进程
从主进程向渲染器进程发送消息时,需要指定接收消息的渲染器进程。 消息需要通过其 WebContents 实例发送到渲染器进程。 此 WebContents 实例包含一个 send 方法,其使用方式与 ipcRenderer.send 相同。
为了演示此模式,我们将构建一个由本机操作系统菜单控制的数字计数器。
对于此演示,您需要将代码添加到您的主进程、渲染进程和 preload 脚本中。完整的代码如下,但我们将在下面的部分中分别解释每个文件。
- main.js
- preload.js
- index.html
- renderer.js
const { app, BrowserWindow, Menu, ipcMain } = require('electron/main')
const path = require('node:path')
function createWindow () {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
const menu = Menu.buildFromTemplate([
{
label: app.name,
submenu: [
{
click: () => mainWindow.webContents.send('update-counter', 1),
label: 'Increment'
},
{
click: () => mainWindow.webContents.send('update-counter', -1),
label: 'Decrement'
}
]
}
])
Menu.setApplicationMenu(menu)
mainWindow.loadFile('index.html')
// Open the DevTools.
mainWindow.webContents.openDevTools()
}
app.whenReady().then(() => {
ipcMain.on('counter-value', (_event, value) => {
console.log(value) // will print value to Node console
})
createWindow()
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
const { contextBridge, ipcRenderer } = require('electron/renderer')
contextBridge.exposeInMainWorld('electronAPI', {
onUpdateCounter: (callback) => ipcRenderer.on('update-counter', (_event, value) => callback(value)),
counterValue: (value) => ipcRenderer.send('counter-value', value)
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://mdn.org.cn/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Menu Counter</title>
</head>
<body>
Current value: <strong id="counter">0</strong>
<script src="./renderer.js"></script>
</body>
</html>
const counter = document.getElementById('counter')
window.electronAPI.onUpdateCounter((value) => {
const oldValue = Number(counter.innerText)
const newValue = oldValue + value
counter.innerText = newValue.toString()
window.electronAPI.counterValue(newValue)
})
1. 使用 webContents 模块发送消息
对于此演示,我们需要首先在主进程中使用 Electron 的 Menu 模块构建一个自定义菜单,该菜单使用 webContents.send API 从主进程向目标渲染器发送 IPC 消息。
const { app, BrowserWindow, Menu, ipcMain } = require('electron')
const path = require('node:path')
function createWindow () {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
const menu = Menu.buildFromTemplate([
{
label: app.name,
submenu: [
{
click: () => mainWindow.webContents.send('update-counter', 1),
label: 'Increment'
},
{
click: () => mainWindow.webContents.send('update-counter', -1),
label: 'Decrement'
}
]
}
])
Menu.setApplicationMenu(menu)
mainWindow.loadFile('index.html')
}
// ...
出于教程的目的,重要的是要注意 click 处理程序通过 update-counter 通道向渲染器进程发送消息(要么是 1,要么是 -1)。
click: () => mainWindow.webContents.send('update-counter', -1)
确保您正在加载以下步骤的 index.html 和 preload.js 入口点!
2. 通过预加载脚本暴露 ipcRenderer.on
与先前的渲染器到主进程示例一样,我们在预加载脚本中使用 contextBridge 和 ipcRenderer 模块,以将 IPC 功能暴露给渲染器进程
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
onUpdateCounter: (callback) => ipcRenderer.on('update-counter', (_event, value) => callback(value))
})
加载预加载脚本后,您的渲染器进程应该可以访问 window.electronAPI.onUpdateCounter() 监听器函数。
出于安全原因,我们不会直接暴露整个 ipcRenderer.on API。 确保尽可能地限制渲染器对 Electron API 的访问。 另外,不要将回调直接传递给 ipcRenderer.on,因为这会通过 event.sender 泄漏 ipcRenderer。 使用仅使用所需的参数调用 callback 的自定义处理程序。
在这种最小示例的情况下,可以在预加载脚本中直接调用 ipcRenderer.on,而不是通过上下文桥暴露它。
const { ipcRenderer } = require('electron')
window.addEventListener('DOMContentLoaded', () => {
const counter = document.getElementById('counter')
ipcRenderer.on('update-counter', (_event, value) => {
const oldValue = Number(counter.innerText)
const newValue = oldValue + value
counter.innerText = newValue
})
})
但是,与通过上下文桥暴露您的预加载 API 相比,这种方法灵活性有限,因为您的监听器无法直接与您的渲染器代码交互。
3. 构建渲染器进程 UI
为了将所有内容整合在一起,我们将创建一个加载的 HTML 文件中的界面,其中包含一个 #counter 元素,我们将使用它来显示值
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://mdn.org.cn/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Menu Counter</title>
</head>
<body>
Current value: <strong id="counter">0</strong>
<script src="./renderer.js"></script>
</body>
</html>
最后,为了使 HTML 文档中的值更新,我们将添加几行 DOM 操作,以便在触发 update-counter 事件时更新 #counter 元素的值。
const counter = document.getElementById('counter')
window.electronAPI.onUpdateCounter((value) => {
const oldValue = Number(counter.innerText)
const newValue = oldValue + value
counter.innerText = newValue.toString()
})
在上面的代码中,我们正在将一个回调传递给从我们的预加载脚本暴露的 window.electronAPI.onUpdateCounter 函数。 第二个 value 参数对应于我们从本机菜单的 webContents.send 调用中传递的 1 或 -1。
可选:返回回复
对于主进程到渲染器进程的 IPC,没有 ipcRenderer.invoke 的等效项。 相反,您可以从 ipcRenderer.on 回调中发送回复回到主进程。
我们可以通过对先前示例中的代码进行轻微修改来演示这一点。 在渲染器进程中,暴露另一个 API,通过 counter-value 通道将回复发送回主进程。
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
onUpdateCounter: (callback) => ipcRenderer.on('update-counter', (_event, value) => callback(value)),
counterValue: (value) => ipcRenderer.send('counter-value', value)
})
const counter = document.getElementById('counter')
window.electronAPI.onUpdateCounter((value) => {
const oldValue = Number(counter.innerText)
const newValue = oldValue + value
counter.innerText = newValue.toString()
window.electronAPI.counterValue(newValue)
})
在主进程中,监听 counter-value 事件并适当地处理它们。
// ...
ipcMain.on('counter-value', (_event, value) => {
console.log(value) // will print value to Node console
})
// ...
模式 4:渲染器到渲染器
使用 ipcMain 和 ipcRenderer 模块在 Electron 中渲染器进程之间发送消息没有直接方法。 为了实现这一点,您有两种选择
- 使用主进程作为渲染器之间的消息代理。 这将涉及从一个渲染器向主进程发送消息,然后主进程将消息转发到另一个渲染器。
- 将 MessagePort 从主进程传递给两个渲染器。 这将在初始设置后允许渲染器之间的直接通信。
对象序列化
Electron 的 IPC 实现使用 HTML 标准 结构化克隆算法 来序列化在进程之间传递的对象,这意味着只有某些类型的对象才能通过 IPC 通道传递。
特别是,DOM 对象(例如 Element、Location 和 DOMMatrix)、由 C++ 类支持的 Node.js 对象(例如 process.env、Stream 的某些成员)以及由 C++ 类支持的 Electron 对象(例如 WebContents、BrowserWindow 和 WebFrame)不能使用结构化克隆进行序列化。