ipcRenderer
进程:
ipcRenderer
是一个 EventEmitter 的实例。 你可以使用它提供的一些方法从渲染进程 (web 页面) 发送同步或异步的消息到主进程。 也可以接收主进程回复的消息。
请从 查看代码示例。
ipcRenderer
模块使用以下方法来监听事件和发送消息。
channel
Stringlistener
Functionevent
IpcRendererEvent
监听 channel
,当接收到新的消息时 listener
会以 listener(event, args...)
的形式被调用。
channel
Stringlistener
Functionevent
IpcRendererEvent...args
any[]
添加一次性 listener
函数。 这个 listener
只会在 channel
下一次收到消息的时候被调用,之后这个监听器会被移除。
channel
Stringlistener
Function...args
any[]
从监听器数组中移除监听 channel
的指定 listener
。
channel
String
移除所有的监听器,当指定 时只移除与其相关的所有监听器。
channel
String...args
any[]
通过channel
向渲染器进程发送异步消息,可以发送任意参数。 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.
If you need to transfer a [MessagePort
][] to the main process, use .
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
String...args
any[]
Returns Promise<any>
- Resolves with the response from the main process.
Send a message to the main process via channel
and expect a result asynchronously. Arguments will be serialized with the , just like [window.postMessage
][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception.
The main process should listen for channel
with ipcMain.handle()
.
例如:
If you need to transfer a [MessagePort
][] to the main process, use .
如果你不需要回复此消息,请考虑使用 ipcRender.sent
。
channel
String...args
any[]
返回 any
- 由 处理程序发送过来的值。
主进程可以使用 ipcMain
监听 channel来接收这些消息,并通过 event.returnValue
设置回复消息。
ipcRenderer.postMessage(channel, message, [transfer])
channel
Stringtransfer
MessagePort[] (optional)
Send a message to the main process, optionally transferring ownership of zero or more [MessagePort
][] objects.
The transferred MessagePort
objects will be available in the main process as objects by accessing the ports
property of the emitted event.
例如:
// Renderer process
const { port1, port2 } = new MessageChannel()
ipcRenderer.postMessage('port', { message: 'hello' }, [port1])
// Main process
ipcMain.on('port', (e, msg) => {
const [port] = e.ports
// ...
})
For more information on using MessagePort
and MessageChannel
, see the MDN documentation.
ipcRenderer.sendTo(webContentsId, channel, ...args)
webContentsId
Numberchannel
String...args
any[]
Sends a message to a window with webContentsId
via channel
.
channel
String...args
any[]
就像 ipcRenderer.send
,不同的是消息会被发送到 host 页面上的 <webview>
元素,而不是主进程。
事件对象
The documentation for the event
object passed to the can be found in the structure docs.