Skip to main content

ipcRenderer

History

从渲染器进程异步地与主进程通信。

进程: 渲染器

🌐 Process: Renderer

info

如果你想从启用上下文隔离的渲染进程调用此 API, 请将 API 调用放在你的 preload 脚本中,并 使用 contextBridge API 暴露 它。

ipcRenderer 模块是一个 事件触发器。它提供了一些方法,让你可以从渲染进程(网页)向主进程发送同步和异步消息。你也可以从主进程接收回复。

🌐 The ipcRenderer module is an EventEmitter. It provides a few methods so you can send synchronous and asynchronous messages from the render process (web page) to the main process. You can also receive replies from the main process.

有关代码示例,请参见 IPC 教程

🌐 See IPC tutorial for code examples.

方法

🌐 Methods

ipcRenderer 模块具有以下方法来监听事件并发送消息:

🌐 The ipcRenderer module has the following method to listen for events and send messages:

ipcRenderer.on(channel, listener)

监听 channel,当有新消息到达时,listener 会被调用,并传入 listener(event, args...)

🌐 Listens to channel, when a new message arrives listener would be called with listener(event, args...).

warning

出于安全原因,不要将 event 参数暴露给渲染进程!将你从渲染进程接收到的任何回调函数用另一个函数封装起来,如:ipcRenderer.on('my-channel', (event, ...args) => callback(...args))。 如果不这样封装回调函数,将会把危险的 Electron API 暴露给渲染进程。更多信息请参阅安全指南

🌐 Do not expose the event argument to the renderer for security reasons! Wrap any callback that you receive from the renderer in another function like this: ipcRenderer.on('my-channel', (event, ...args) => callback(...args)). Not wrapping the callback in such a function would expose dangerous Electron APIs to the renderer process. See the security guide for more info.

ipcRenderer.off(channel, listener)

从指定的 channel 的监听器数组中移除指定的 listener

🌐 Removes the specified listener from the listener array for the specified channel.

ipcRenderer.once(channel, listener)

为该事件添加一次性的 listener 函数。这个 listener 只会在下一次向 channel 发送消息时被调用,之后它将被移除。

🌐 Adds a one time listener function for the event. This listener is invoked only the next time a message is sent to channel, after which it is removed.

ipcRenderer.addListener(channel, listener)

[ipcRenderer.on](#ipcrendereronchannel-listener) 的别名。

🌐 Alias for ipcRenderer.on.

ipcRenderer.removeListener(channel, listener)

[ipcRenderer.off](#ipcrendereroffchannel-listener) 的别名。

🌐 Alias for ipcRenderer.off.

ipcRenderer.removeAllListeners([channel])

  • channel 字符串(可选)

从指定的 channel 中移除所有监听器。如果未指定通道,则从所有通道中移除所有监听器。

🌐 Removes all listeners from the specified channel. Removes all listeners from all channels if no channel is specified.

ipcRenderer.send(channel, ...args)

  • channel 字符串
  • ...args any[]

通过 channel 向主进程发送异步消息,并附带参数。参数将使用 结构化克隆算法 序列化,就像 window.postMessage 一样,因此原型链将不会被包含。发送函数、Promise、Symbol、WeakMap 或 WeakSet 会抛出异常。

🌐 Send an asynchronous message to the main process via channel, along with arguments. Arguments will be serialized with the Structured Clone Algorithm, just like window.postMessage, so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception.

注意: 发送非标准的 JavaScript 类型,例如 DOM 对象或特殊的 Electron 对象,会引发异常。

由于主进程不支持像 ImageBitmapFileDOMMatrix 等 DOM 对象,因此这些对象无法通过 Electron 的 IPC 发送到主进程,因为主进程无法对它们进行解码。尝试通过 IPC 发送此类对象将导致错误。

主进程通过使用 ipcMain 模块监听 channel 来处理它。

🌐 The main process handles it by listening for channel with the ipcMain module.

如果你需要将 MessagePort 转移到主进程,请使用 ipcRenderer.postMessage

🌐 If you need to transfer a MessagePort to the main process, use ipcRenderer.postMessage.

如果你想从主进程接收单个响应,比如方法调用的结果,可以考虑使用 ipcRenderer.invoke

🌐 If you want to receive a single response from the main process, like the result of a method call, consider using ipcRenderer.invoke.

ipcRenderer.invoke(channel, ...args)

  • channel 字符串
  • ...args any[]

返回 Promise<any> - 使用主进程的响应进行解析。

🌐 Returns Promise<any> - Resolves with the response from the main process.

通过 channel 向主进程发送消息,并异步等待结果。参数将使用 结构化克隆算法 序列化,就像 window.postMessage 一样,因此原型链不会被包含。发送函数、Promise、Symbol、WeakMap 或 WeakSet 将抛出异常。

🌐 Send a message to the main process via channel and expect a result asynchronously. Arguments will be serialized with the Structured Clone Algorithm, just like window.postMessage, so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception.

主进程应使用 ipcMain.handle() 监听 channel

🌐 The main process should listen for channel with ipcMain.handle().

例如:

🌐 For example:

// Renderer process
ipcRenderer.invoke('some-name', someArgument).then((result) => {
// ...
})

// Main process
ipcMain.handle('some-name', async (event, someArgument) => {
const result = await doSomeWork(someArgument)
return result
})

如果你需要将 MessagePort 转移到主进程,请使用 ipcRenderer.postMessage

🌐 If you need to transfer a MessagePort to the main process, use ipcRenderer.postMessage.

如果你不需要回复这条消息,可以考虑使用 ipcRenderer.send

🌐 If you do not need a response to the message, consider using ipcRenderer.send.

note

发送非标准的 JavaScript 类型(例如 DOM 对象或特殊的 Electron 对象)将会抛出异常。

由于主进程不支持诸如 ImageBitmapFileDOMMatrix 等 DOM 对象,因此这些对象不能通过 Electron 的 IPC 发送到主进程,因为主进程无法解码它们。尝试通过 IPC 发送此类对象将导致错误。

note

如果主进程中的处理程序抛出错误, invoke 返回的 promise 将被拒绝。 但是,渲染进程中的 Error 对象 不会与主进程中抛出的对象相同。

ipcRenderer.sendSync(channel, ...args)

  • channel 字符串
  • ...args any[]

返回 any - 由 ipcMain 处理程序返回的值。

🌐 Returns any - The value sent back by the ipcMain handler.

通过 channel 向主进程发送消息,并同步地期望得到结果。参数将使用 结构化克隆算法 序列化,就像 window.postMessage 一样,因此原型链不会被包含。发送函数、Promise、Symbol、WeakMap 或 WeakSet 将抛出异常。

🌐 Send a message to the main process via channel and expect a result synchronously. Arguments will be serialized with the Structured Clone Algorithm, just like window.postMessage, so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception.

注意: 发送非标准的 JavaScript 类型,例如 DOM 对象或特殊的 Electron 对象,会引发异常。

由于主进程不支持像 ImageBitmapFileDOMMatrix 等 DOM 对象,因此这些对象无法通过 Electron 的 IPC 发送到主进程,因为主进程无法对它们进行解码。尝试通过 IPC 发送此类对象将导致错误。

主进程通过使用 ipcMain 模块监听 channel 来处理它,并通过设置 event.returnValue 来回应。

🌐 The main process handles it by listening for channel with ipcMain module, and replies by setting event.returnValue.

warning

发送同步消息会阻塞整个渲染进程,直到收到回复,因此仅在万不得已时使用此方法。使用异步版本 invoke() 要好得多。

ipcRenderer.postMessage(channel, message, [transfer])

  • channel 字符串
  • message 任何
  • transfer MessagePort[](可选)

向主进程发送消息,可选择性地转移零个或多个 MessagePort 对象的所有权。

🌐 Send a message to the main process, optionally transferring ownership of zero or more MessagePort objects.

被转移的 MessagePort 对象可以在主进程中作为 MessagePortMain 对象使用,通过访问触发事件的 ports 属性。

🌐 The transferred MessagePort objects will be available in the main process as MessagePortMain objects by accessing the ports property of the emitted event.

例如:

🌐 For example:

// Renderer process
const { port1, port2 } = new MessageChannel()
ipcRenderer.postMessage('port', { message: 'hello' }, [port1])

// Main process
ipcMain.on('port', (e, msg) => {
const [port] = e.ports
// ...
})

关于使用 MessagePortMessageChannel 的更多信息,请参阅 MDN 文档

🌐 For more information on using MessagePort and MessageChannel, see the MDN documentation.

ipcRenderer.sendToHost(channel, ...args)

  • channel 字符串
  • ...args any[]

类似 ipcRenderer.send,但事件将发送到主页面中的 <webview> 元素,而不是主进程。

🌐 Like ipcRenderer.send but the event will be sent to the <webview> element in the host page instead of the main process.