ipcMain
從主程序非同步地與渲染器程序通訊。
程序:主程序
ipcMain
模組是一個 EventEmitter。當在主程序中使用時,它會處理從渲染器程序(網頁)傳送的非同步和同步訊息。從渲染器傳送的訊息將會發送到此模組。
有關使用範例,請查看IPC 教學。
傳送訊息
也可以從主程序傳送訊息到渲染器程序,請參閱 webContents.send 以取得更多資訊。
- 傳送訊息時,事件名稱為
channel
。 - 要回覆同步訊息,您需要設定
event.returnValue
。 - 要將非同步訊息傳送回傳送者,您可以使用
event.reply(...)
。這個輔助方法將會自動處理來自非主框架(例如 iframe)的訊息,而event.sender.send(...)
則始終會傳送到主框架。
方法
ipcMain
模組有下列方法可監聽事件
ipcMain.on(channel, listener)
channel
字串listener
函式event
IpcMainEvent...args
any[]
監聽 channel
,當新訊息抵達時,會使用 listener(event, args...)
呼叫 listener
。
ipcMain.off(channel, listener)
channel
字串listener
函式event
IpcMainEvent...args
any[]
從指定 channel
的監聽器陣列中移除指定的 listener
。
ipcMain.once(channel, listener)
channel
字串listener
函式event
IpcMainEvent...args
any[]
為事件新增一個一次性的 listener
函式。只有在下次將訊息傳送到 channel
時,才會呼叫此 listener
,之後便會移除它。
ipcMain.addListener(channel, listener)
channel
字串listener
函式event
IpcMainEvent...args
any[]
ipcMain.on
的別名。
ipcMain.removeListener(channel, listener)
channel
字串listener
函式...args
any[]
ipcMain.off
的別名。
ipcMain.removeAllListeners([channel])
channel
字串 (選用)
從指定的 channel
移除所有監聽器。如果未指定 channel,則從所有 channel 移除所有監聽器。
ipcMain.handle(channel, listener)
channel
字串listener
函式<Promise<any> | any>event
IpcMainInvokeEvent...args
any[]
為可 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
any[]
處理單一可 invoke
的 IPC 訊息,然後移除監聽器。請參閱 ipcMain.handle(channel, listener)
。
ipcMain.removeHandler(channel)
channel
字串
移除 channel
的任何處理常式 (如果存在)。