ipcMain
从主进程到渲染进程的异步通信。
ProcessMain
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)
channelstringlistenerFunctioneventIpcMainEvent...argsany[]
监听 channel, 当新消息到达,将通过 listener(event, args...) 调用 listener。
ipcMain.off(channel, listener)
History
| Version(s) | Changes |
|---|---|
None | API ADDED |
channelstringlistenerFunctioneventIpcMainEvent...argsany[]
为特定的 channel 从监听队列中删除特定的 listener 监听者.
ipcMain.once(channel, listener)
channelstringlistenerFunctioneventIpcMainEvent...argsany[]
添加一次性 listener 函数。这个 listener 只会在 channel下一次收到消息的时候被调用,之后这个监听器会被移除。
ipcMain.addListener(channel, listener)
channelstringlistenerFunctioneventIpcMainEvent...argsany[]
Alias for ipcMain.on.
ipcMain.removeListener(channel, listener)
channelstringlistenerFunction...argsany[]
Alias for ipcMain.off.
ipcMain.removeAllListeners([channel])
channelstring (optional)
Removes all listeners from the specified channel. Removes all listeners from all channels if no channel is specified.
ipcMain.handle(channel, listener)
History
| Version(s) | Changes |
|---|---|
None | API ADDED |
channelstringlistenerFunction<Promise<any> | any>eventIpcMainInvokeEvent...argsany[]
为一个 invokeable的IPC 添加一个handler。每当一个渲染进程调用 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 与传递给常规事件侦听器的相同。里面包含了哪些 WebContents 是调用请求的来源
通过handle在主线程抛出的异常并不易读,那是因为他们已经被序列化了。只有原始错误中的 message 属性可提供给渲染进程。详情请参阅 #24427
ipcMain.handleOnce(channel, listener)
History
| Version(s) | Changes |
|---|---|
None | API ADDED |
channelstringlistenerFunction<Promise<any> | any>eventIpcMainInvokeEvent...argsany[]
处理单个 invokeable 可触发的 IPC 消息,然后移除侦听器。详见 ipcMain.handle(channel, listener)
ipcMain.removeHandler(channel)
History
| Version(s) | Changes |
|---|---|
None | API ADDED |
channelstring
移除 channel的所有处理程序,若存在。