Electron 中的 MessagePorts
MessagePort
是一種 Web 功能,允許在不同上下文之間傳遞訊息。它類似於 window.postMessage
,但在不同的通道上進行。本文檔的目標是描述 Electron 如何擴展通道訊息模型,並提供一些您可能在應用程式中使用 MessagePorts 的範例。
以下是一個簡短的 MessagePort 及其運作方式範例
// MessagePorts are created in pairs. A connected pair of message ports is
// called a channel.
const channel = new MessageChannel()
// The only difference between port1 and port2 is in how you use them. Messages
// sent to port1 will be received by port2 and vice-versa.
const port1 = channel.port1
const port2 = channel.port2
// It's OK to send a message on the channel before the other end has registered
// a listener. Messages will be queued until a listener is registered.
port2.postMessage({ answer: 42 })
// Here we send the other end of the channel, port1, to the main process. It's
// also possible to send MessagePorts to other frames, or to Web Workers, etc.
ipcRenderer.postMessage('port', null, [port1])
// In the main process, we receive the port.
ipcMain.on('port', (event) => {
// When we receive a MessagePort in the main process, it becomes a
// MessagePortMain.
const port = event.ports[0]
// MessagePortMain uses the Node.js-style events API, rather than the
// web-style events API. So .on('message', ...) instead of .onmessage = ...
port.on('message', (event) => {
// data is { answer: 42 }
const data = event.data
})
// MessagePortMain queues messages until the .start() method has been called.
port.start()
})
通道訊息 API 文件是了解 MessagePorts 如何運作的好方法。
主程序中的 MessagePorts
在渲染程序中,MessagePort
類別的行為與在 Web 上完全相同。然而,主程序不是網頁,它沒有 Blink 整合,因此沒有 MessagePort
或 MessageChannel
類別。為了處理主程序中的 MessagePorts 並與之互動,Electron 新增了兩個新類別:MessagePortMain
和 MessageChannelMain
。這些類別的行為與渲染程序中對應的類別類似。
可以在渲染程序或主程序中建立 MessagePort
物件,並使用 ipcRenderer.postMessage
和 WebContents.postMessage
方法來回傳遞。請注意,像 send
和 invoke
這樣的常用 IPC 方法不能用於傳輸 MessagePort
,只有 postMessage
方法可以傳輸 MessagePort
。
透過經由主程序傳遞 MessagePort
,您可以連接兩個原本可能無法通訊的頁面 (例如,由於同源限制)。
擴充功能:close
事件
Electron 為 MessagePort
新增了一項 Web 上不存在的功能,以使 MessagePorts 更加實用。那就是 close
事件,當通道的另一端關閉時會發出此事件。連接埠也可以透過垃圾回收來隱含關閉。
在渲染程序中,您可以透過指定 port.onclose
或呼叫 port.addEventListener('close', ...)
來監聽 close
事件。在主程序中,您可以透過呼叫 port.on('close', ...)
來監聽 close
事件。
範例使用案例
在兩個渲染程序之間設定 MessageChannel
在此範例中,主程序會設定 MessageChannel,然後將每個連接埠傳送到不同的渲染程序。這允許渲染程序互相傳送訊息,而無需將主程序用作中介。
const { BrowserWindow, app, MessageChannelMain } = require('electron')
app.whenReady().then(async () => {
// create the windows.
const mainWindow = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: false,
preload: 'preloadMain.js'
}
})
const secondaryWindow = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: false,
preload: 'preloadSecondary.js'
}
})
// set up the channel.
const { port1, port2 } = new MessageChannelMain()
// once the webContents are ready, send a port to each webContents with postMessage.
mainWindow.once('ready-to-show', () => {
mainWindow.webContents.postMessage('port', null, [port1])
})
secondaryWindow.once('ready-to-show', () => {
secondaryWindow.webContents.postMessage('port', null, [port2])
})
})
然後,在您的預載入腳本中,您會透過 IPC 接收連接埠並設定監聽器。
const { ipcRenderer } = require('electron')
ipcRenderer.on('port', e => {
// port received, make it globally available.
window.electronMessagePort = e.ports[0]
window.electronMessagePort.onmessage = messageEvent => {
// handle message
}
})
在此範例中,messagePort 直接繫結到 window
物件。最好使用 contextIsolation
,並為每個預期的訊息設定特定的 contextBridge 呼叫,但為了此範例的簡單起見,我們不使用。您可以在此頁面下方找到一個上下文隔離的範例,請參閱 在主程序和上下文隔離頁面的主要世界之間直接通訊。
這表示 window.electronMessagePort 是全域可用的,您可以從應用程式中的任何位置呼叫 postMessage
以將訊息傳送到另一個渲染程序。
// elsewhere in your code to send a message to the other renderers message handler
window.electronMessagePort.postMessage('ping')
Worker 程序
在此範例中,您的應用程式有一個以隱藏視窗實作的 Worker 程序。您希望應用程式頁面能夠直接與 Worker 程序通訊,而不會產生經由主程序轉發的效能負擔。
const { BrowserWindow, app, ipcMain, MessageChannelMain } = require('electron')
app.whenReady().then(async () => {
// The worker process is a hidden BrowserWindow, so that it will have access
// to a full Blink context (including e.g. <canvas>, audio, fetch(), etc.)
const worker = new BrowserWindow({
show: false,
webPreferences: { nodeIntegration: true }
})
await worker.loadFile('worker.html')
// The main window will send work to the worker process and receive results
// over a MessagePort.
const mainWindow = new BrowserWindow({
webPreferences: { nodeIntegration: true }
})
mainWindow.loadFile('app.html')
// We can't use ipcMain.handle() here, because the reply needs to transfer a
// MessagePort.
// Listen for message sent from the top-level frame
mainWindow.webContents.mainFrame.ipc.on('request-worker-channel', (event) => {
// Create a new channel ...
const { port1, port2 } = new MessageChannelMain()
// ... send one end to the worker ...
worker.webContents.postMessage('new-client', null, [port1])
// ... and the other end to the main window.
event.senderFrame.postMessage('provide-worker-channel', null, [port2])
// Now the main window and the worker can communicate with each other
// without going through the main process!
})
})
<script>
const { ipcRenderer } = require('electron')
const doWork = (input) => {
// Something cpu-intensive.
return input * 2
}
// We might get multiple clients, for instance if there are multiple windows,
// or if the main window reloads.
ipcRenderer.on('new-client', (event) => {
const [ port ] = event.ports
port.onmessage = (event) => {
// The event data can be any serializable object (and the event could even
// carry other MessagePorts with it!)
const result = doWork(event.data)
port.postMessage(result)
}
})
</script>
<script>
const { ipcRenderer } = require('electron')
// We request that the main process sends us a channel we can use to
// communicate with the worker.
ipcRenderer.send('request-worker-channel')
ipcRenderer.once('provide-worker-channel', (event) => {
// Once we receive the reply, we can take the port...
const [ port ] = event.ports
// ... register a handler to receive results ...
port.onmessage = (event) => {
console.log('received result:', event.data)
}
// ... and start sending it work!
port.postMessage(21)
})
</script>
回覆串流
Electron 的內建 IPC 方法僅支援兩種模式:發送即忘 (例如 send
) 或請求-回應 (例如 invoke
)。使用 MessageChannels,您可以實作「回應串流」,其中單一請求會以資料串流回應。
const makeStreamingRequest = (element, callback) => {
// MessageChannels are lightweight--it's cheap to create a new one for each
// request.
const { port1, port2 } = new MessageChannel()
// We send one end of the port to the main process ...
ipcRenderer.postMessage(
'give-me-a-stream',
{ element, count: 10 },
[port2]
)
// ... and we hang on to the other end. The main process will send messages
// to its end of the port, and close it when it's finished.
port1.onmessage = (event) => {
callback(event.data)
}
port1.onclose = () => {
console.log('stream ended')
}
}
makeStreamingRequest(42, (data) => {
console.log('got response data:', data)
})
// We will see "got response data: 42" 10 times.
ipcMain.on('give-me-a-stream', (event, msg) => {
// The renderer has sent us a MessagePort that it wants us to send our
// response over.
const [replyPort] = event.ports
// Here we send the messages synchronously, but we could just as easily store
// the port somewhere and send messages asynchronously.
for (let i = 0; i < msg.count; i++) {
replyPort.postMessage(msg.element)
}
// We close the port when we're done to indicate to the other end that we
// won't be sending any more messages. This isn't strictly necessary--if we
// didn't explicitly close the port, it would eventually be garbage
// collected, which would also trigger the 'close' event in the renderer.
replyPort.close()
})
在主程序和上下文隔離頁面的主要世界之間直接通訊
啟用上下文隔離後,從主程序到渲染程序的 IPC 訊息會傳遞到隔離的世界,而不是傳遞到主要世界。有時您希望直接將訊息傳遞到主要世界,而無需逐步通過隔離的世界。
const { BrowserWindow, app, MessageChannelMain } = require('electron')
const path = require('node:path')
app.whenReady().then(async () => {
// Create a BrowserWindow with contextIsolation enabled.
const bw = new BrowserWindow({
webPreferences: {
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
})
bw.loadURL('index.html')
// We'll be sending one end of this channel to the main world of the
// context-isolated page.
const { port1, port2 } = new MessageChannelMain()
// It's OK to send a message on the channel before the other end has
// registered a listener. Messages will be queued until a listener is
// registered.
port2.postMessage({ test: 21 })
// We can also receive messages from the main world of the renderer.
port2.on('message', (event) => {
console.log('from renderer main world:', event.data)
})
port2.start()
// The preload script will receive this IPC message and transfer the port
// over to the main world.
bw.webContents.postMessage('main-world-port', null, [port1])
})
const { ipcRenderer } = require('electron')
// We need to wait until the main world is ready to receive the message before
// sending the port. We create this promise in the preload so it's guaranteed
// to register the onload listener before the load event is fired.
const windowLoaded = new Promise(resolve => {
window.onload = resolve
})
ipcRenderer.on('main-world-port', async (event) => {
await windowLoaded
// We use regular window.postMessage to transfer the port from the isolated
// world to the main world.
window.postMessage('main-world-port', '*', event.ports)
})
<script>
window.onmessage = (event) => {
// event.source === window means the message is coming from the preload
// script, as opposed to from an <iframe> or other source.
if (event.source === window && event.data === 'main-world-port') {
const [ port ] = event.ports
// Once we have the port, we can communicate directly with the main
// process.
port.onmessage = (event) => {
console.log('from main process:', event.data)
port.postMessage(event.data.test * 2)
}
}
}
</script>