ipcMain
從主程序非同步地與渲染程序溝通。
程序: 主程序
ipcMain
模組是一個 事件發射器。當在主程序中使用時,它會處理從渲染程序(網頁)發送的非同步和同步訊息。從渲染程序發送的訊息將會發射到此模組。
如需使用範例,請查看 IPC 教學。
發送訊息
也可以從主程序發送訊息到渲染程序,請參閱 webContents.send 以取得更多資訊。
- 當發送訊息時,事件名稱為
channel
。 - 要回覆同步訊息,您需要設定
event.returnValue
。 - 要將非同步訊息發送回發送者,您可以使用
event.reply(...)
。這個輔助方法將自動處理來自非主要影格(例如 iframes)的訊息,而event.sender.send(...)
將始終發送到主要影格。
方法
ipcMain
模組具有以下方法來監聽事件
ipcMain.on(channel, listener)
channel
字串listener
函數event
IpcMainEvent...args
任何陣列
監聽 channel
,當新訊息到達時,將會呼叫 listener
,並帶有 listener(event, args...)
。
ipcMain.off(channel, listener)
channel
字串listener
函數event
IpcMainEvent...args
任何陣列
從指定 channel
的監聽器陣列中移除指定的 listener
。
ipcMain.once(channel, listener)
channel
字串listener
函數event
IpcMainEvent...args
任何陣列
為事件新增一次性的 listener
函數。此 listener
僅在下次訊息發送到 channel
時調用,之後即會移除。
ipcMain.addListener(channel, listener)
channel
字串listener
函數event
IpcMainEvent...args
任何陣列
ipcMain.on
的別名。
ipcMain.removeListener(channel, listener)
channel
字串listener
函數...args
任何陣列
ipcMain.off
的別名。
ipcMain.removeAllListeners([channel])
channel
字串 (選填)
從指定的 channel
移除所有監聽器。如果未指定 channel,則從所有頻道移除所有監聽器。
ipcMain.handle(channel, listener)
channel
字串listener
函數<Promise<any> | any>event
IpcMainInvokeEvent...args
任何陣列
為可 invoke
的 IPC 新增處理程序。每當渲染程序呼叫 ipcRenderer.invoke(channel, ...args)
時,將會呼叫此處理程序。
如果 listener
傳回 Promise,則 promise 的最終結果將作為回覆傳回給遠端呼叫者。否則,listener 的傳回值將用作回覆的值。
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 是 invoke 請求來源的資訊。
透過主程序中的 handle
拋出的錯誤不是透明的,因為它們被序列化,並且僅將原始錯誤中的 message
屬性提供給渲染程序。請參閱 #24427 以取得詳細資訊。
ipcMain.handleOnce(channel, listener)
channel
字串listener
函數<Promise<any> | any>event
IpcMainInvokeEvent...args
任何陣列
處理單個可 invoke
的 IPC 訊息,然後移除監聽器。請參閱 ipcMain.handle(channel, listener)
。
ipcMain.removeHandler(channel)
channel
字串
移除 channel
的任何處理程序(如果存在)。