跳转到主内容

ipcMain

从主进程到渲染进程的异步通信。

Process: Main

ipcRenderer 是一个 EventEmitter 的实例。 当在主进程中使用时,它处理从渲染器进程(网页)发送出来的异步和同步信息。 从渲染器进程发送的消息将被发送到该模块。

For usage examples, check out the IPC tutorial.

发送消息​

It is also possible to send messages from the main process to the renderer process, see webContents.send for more information.

  • 发送消息时,事件名称为channel 。
  • 回复同步信息时,需要设置event.returnValue。
  • 可以使用event.reply(...)将异步消息发送回发送者。 此方法将自动处理从非主 frame 发送的消息(比如: iframes)。相应的发送方法是: event.sender.send(...) 它将总是把消息发送到主 frame

方法​

The ipcMain module has the following methods to listen for events:

ipcMain.on(channel, listener)​

  • channel string
  • listener Function

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

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

Alias for ipcMain.on.

ipcMain.removeListener(channel, listener)​

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

Alias for ipcMain.off.

ipcMain.removeAllListeners([channel])​

  • channel string (optional)

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

ipcMain.handle(channel, listener)​

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

为一个 invokeable的IPC 添加一个handler。 每当一个渲染进程调用 ipcRenderer.invoke(channel, ...args) 时这个处理器就会被调用。

如果 listener 返回一个 Promise,那么 Promise 的最终结果就是远程调用的返回值。 否则, 监听器的返回值将被用来作为应答值。

Main Process
ipcMain.handle('my-invokable-ipc', async (event, ...args) => {
const result = await somePromise(...args)
return result
})
Renderer Process
async () => {
const result = await ipcRenderer.invoke('my-invokable-ipc', arg1, arg2)
// ...
}

传递给处理器的第一个参数的 event 与传递给常规事件侦听器的相同。 里面包含了哪些 WebContents 是调用请求的来源

通过handle在主线程抛出的异常并不易读,那是因为他们已经被序列化了。只有原始错误中的 message 属性可提供给渲染进程。 详情请参阅 #24427

ipcMain.handleOnce(channel, listener)​

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

处理单个 invokeable 可触发的 IPC 消息,然后移除侦听器。 详见 ipcMain.handle(channel, listener)

ipcMain.removeHandler(channel)​

  • channel string

移除 channel的所有处理程序,若存在。