问题描述
在 electron 中,可以通过 ipcRenderer 将同步消息从 IpcRenderer 发送到 IpcMain.sendSync('同步消息', 'ping')
.
还可以使用 window.webContents.send('ping', 'whooooooooh!')
将 async 消息从 IpcMain 发送到 IpcRenderer
但是有什么方法可以将 sync 消息从 IpcMain 发送到 IpcRenderer?
ipcMain
没有这个功能.但是,您可以通过以下步骤异步获得几乎相同的结果:
- 将仅在同步调用之后运行的代码放在
ipcMain
回调中. - 使用
event.sender.send
在渲染器进程中使用结果回复 ipc 消息
使用这种方法的 sum 虚拟示例如下所示:
main.js
const {app, BrowserWindow, ipcMain} = require('electron')常量路径 = 要求('路径')app.once('准备好了', () => {让 win = new BrowserWindow()//必须运行同步",即只有在结果准备好之后const doJobWithResult = (res) =>{控制台.log(res)}win.webContents.once('dom-ready', () => {win.web 内容.send('求和请求', 23, 98, 3, 61)ipcMain.once('sum-reply', (event, sum) => {doJobWithResult(sum)})})win.loadURL(path.resolve(__dirname, 'test.html'))})
renderer.js(引用自 test.html)
const {ipcRenderer} = require('electron')window.onload = () =>{const add = (a, b) =>{返回 a + b}ipcRenderer.on('sum-request', (event, ...args) => {event.sender.send('sum-reply', [...args].reduce(add, 0))})}
In electron, It is possible to send sync message from IpcRenderer to IpcMain via ipcRenderer.sendSync('synchronous-message', 'ping')
.
Also possible to send async message from IpcMain to IpcRenderer using window.webContents.send('ping', 'whoooooooh!')
but is there any way to send sync message from IpcMain to IpcRenderer?
There is no such functionality of ipcMain
. However, you can achieve almost the same result asynchronously with the following steps:
- Place your code which you would run only after the synchronous call in an
ipcMain
callback. - Reply to ipc message in renderer process with the result using
event.sender.send
A dummy example of sum using this approach looks like the following:
main.js
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
app.once('ready', () => {
let win = new BrowserWindow()
// have to run "sync", that is only after result is ready
const doJobWithResult = (res) => {
console.log(res)
}
win.webContents.once('dom-ready', () => {
win.webContents
.send('sum-request', 23, 98, 3, 61)
ipcMain.once('sum-reply', (event, sum) => {
doJobWithResult(sum)
})
})
win.loadURL(path.resolve(__dirname, 'test.html'))
})
renderer.js (referred from test.html)
const {ipcRenderer} = require('electron')
window.onload = () => {
const add = (a, b) => {
return a + b
}
ipcRenderer.on('sum-request', (event, ...args) => {
event.sender.send('sum-reply', [...args].reduce(add, 0))
})
}
这篇关于将同步消息从 IpcMain 发送到 IpcRenderer - Electron的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!