在electron中,可以通过ipcRenderer.sendSync('synchronous-message', 'ping')
从IpcRenderer向IpcMain发送同步消息。
还可以使用window.webContents.send('ping', 'whoooooooh!')
但有没有办法从IpcMain向IpcRenderer发送同步消息?
答案 0 :(得分:9)
在渲染器进程(同步)中访问主流程对象的最简单方法
// In renderer process (web page).
const { ipcRenderer } = require('electron');
let exec = eval => ipcRenderer.sendSync('synchronous-message', eval);
exec("win.setSize(500,500)");
console.log(exec("win.getBounds()"));
console.log(exec("app.getVersion()"));
// In the Main process.
ipcMain.on('synchronous-message', (event, arg) => {
event.returnValue = eval(arg);
})
这是将msg从Main进程发送到渲染器进程的方式。(官方示例)
// In renderer process (web page).
ipcRenderer.on('test', (event, arg) => {
console.log(arg) // 123
})
// In the Main process.(after loaded you can send msg to renderer process)
win.webContents.on('did-finish-load', () => {
win.webContents.send('test',123);
})
答案 1 :(得分:5)
ipcMain
* 没有此类功能。但是,您可以通过以下步骤异步实现几乎相同的结果:
ipcMain
回调中仅在同步调用之后运行。event.sender.send
使用此方法求和的一个虚拟示例如下所示:
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(来自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))
})
}
*我想这是因为从主节点到渲染器同步调用会阻塞主节点js进程,它毕竟也会为渲染器进程提供服务。
答案 2 :(得分:0)
我试图做同样的事情,而我得到的最接近的结果是,首先从IPCRenderer发送消息,然后从接收到的IPCMain事件中返回您想要的代码片段:
// In renderer process (web page).
const ipcRenderer = require('electron').ipcRenderer;
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong"
// In the Main process.
ipcMain.on('synchronous-message', function(event, arg) {
console.log(arg); // prints "ping"
event.returnValue = 'pong';
});
答案 3 :(得分:-1)
是的,可以将发送同步消息从IpcRenderer发送到IpcMain
let {ipcRenderer} = require('electron');
ipcRenderer.sendSync('sync', 'Im the message from the renderer');
// Listen for sync message from renderer process
ipcMain.on('sync', (event, arg) => {
console.log(arg); // Print Im the message from the renderer
});
我建议您访问VJEKOSLAV RATKAJEC的这篇文章,他很好地解释了de ipcMain与ipcRenderer之间的通信,反之亦然。
链接:http://electron.rocks/different-ways-to-communicate-between-main-and-renderer-process/