跳转到主要内容

ipcMain

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

进程: 主进程

ipcMain 模块是一个 事件发射器。在主进程中使用时,它处理来自渲染进程(网页)的异步和同步消息。来自渲染进程发送的消息将在此模块中被触发。

有关使用示例,请查看 IPC 教程

发送消息

也可以从主进程向渲染进程发送消息,请参阅 webContents.send 以获取更多信息。

  • 发送消息时,事件名称是 channel(通道)。
  • 要回复同步消息,需要设置 event.returnValue
  • 要将异步消息发送回发送者,可以使用 event.reply(...)。此辅助方法将自动处理来自非主框架的帧(例如 iframe)的消息,而 event.sender.send(...) 将始终发送到主框架。

方法

ipcMain 模块具有以下方法来监听事件

ipcMain.on(channel, listener)

  • channel string
  • listener Function

监听 channel,当新消息到达时,将调用 listener(event, args...)

ipcMain.off(channel, listener)

  • channel string
  • listener Function

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

ipcMain.once(channel, listener)

  • channel string
  • listener Function

为事件添加一次性 listener 函数。此 listener 仅在下次向 channel 发送消息时调用,之后将被移除。

ipcMain.addListener(channel, listener)

  • channel string
  • listener Function

ipcMain.on 的别名。

ipcMain.removeListener(channel, listener)

  • channel string
  • listener Function
    • ...args any[]

ipcMain.off 的别名。

ipcMain.removeAllListeners([channel])

  • channel string (可选)

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

ipcMain.handle(channel, listener)

  • channel string
  • listener Function<Promise<any> | any>

为可 invoke 的 IPC 添加处理程序。每当渲染进程调用 ipcRenderer.invoke(channel, ...args) 时,将调用此处理程序。

如果 listener 返回 Promise,则 Promise 最终的结果将作为对远程调用者的回复返回。否则,监听器的返回值将用作回复的值。

主进程
ipcMain.handle('my-invokable-ipc', async (event, ...args) => {
const result = await somePromise(...args)
return result
})
渲染器进程
async () => {
const result = await ipcRenderer.invoke('my-invokable-ipc', arg1, arg2)
// ...
}

传递给处理程序的 event 与传递给常规事件监听器的 event 相同。它包含有关发起 invoke 请求的 WebContents 的信息。

通过 handle 在主进程中抛出的错误不会透明地传递,它们会被序列化,并且只有原始错误的 message 属性提供给渲染进程。有关详细信息,请参阅 #24427

ipcMain.handleOnce(channel, listener)

  • channel string
  • listener Function<Promise<any> | any>

处理单个可 invoke 的 IPC 消息,然后移除监听器。请参阅 ipcMain.handle(channel, listener)

ipcMain.removeHandler(channel)

  • channel string

如果存在,则移除 channel 的任何处理程序。