electron主进程和渲染进程通信
本文转载自:https://newsn.net/
electron分为主进程和渲染进程,主进程和渲染进程进行通信的时候,就需要用到ipc这个特性。而ipc又分为ipcMain和ipcRenderer两个方面,分别用于主进程和渲染进程。本文中,苏南大叔就ipcMain和ipcRenderer这两个特性进行简要描述。

本文例子,来自于 https://electron.org.cn/doc/api/ipc-main.html 。一共有三个概念,channel事件名称(频道),async异步,sync同步。本文的测试环境是:[email protected]。
async异步消息的发送与返回
渲染进程使用ipcRenderer.send发送异步消息,然后使用on事件监控主进程的返回值。主进程使用on事件监听消息,使用event.sender.send返回数据。
渲染进程和主进程进行关联,使用的关键词就是:channel。下面是个使用的简单范例:
index.html:
const {ipcRenderer} = require('electron')ipcRenderer.send('asynchronous-message', 'ping')
ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg) // prints "pong"
})
main.js:
const {ipcMain} = require('electron')ipcMain.on('asynchronous-message', (event, arg) => {
console.log(arg) // prints "ping"
event.sender.send('asynchronous-reply', 'pong')
});
function createWindow () {
//...
}
app.on('ready', createWindow)
sync同步消息的发送与返回
渲染进程使用ipcRenderer.sendSync发送同步消息。主进程使用on事件监控消息,使用event.returnValue返回数据给渲染进程。返回值在渲染进程中,就直接体现为ipcRenderer.sendSync的函数返回值。
因为这种同步sync的方式,会阻碍渲染进程的渲染,所以,应该尽量避免使用这种同步sync方式。
index.html:
const { ipcRenderer } = require('electron')console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"
main.js:
const {ipcMain} = require('electron')ipcMain.on('synchronous-message', (event, arg) => {
console.log(arg) // prints "ping"
event.returnValue = 'pong'
})
function createWindow () {
//...
}
app.on('ready', createWindow)
值得注意的是:主进程和渲染进程的输出位置是不一样的。那么,读者所看到的ping和pong也不是同一个位置。具体可以参见下面这篇文字:
主进程主动发送消息到渲染进程
在官方的范例中,苏南大叔找到的demo,都是渲染进程主动发起事件的。不过,主进程也应该有可能有需要发起事件请求。对吧?
主进程主动发送消息的理论依据是:async异步消息的返回值方法:event.sender.send。根据官方的说法,event.sender就是webContents,两者是同一个事物。那么,主进程主动异步发送消息的代码如下:
当然,下面的代码,是苏南大叔自己写的,并没有得到其他地方的代码呼应验证,大家请谨慎参考。
index.html:
const { ipcRenderer } = require('electron')ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg) // prints "pong!!!"
})
这个代码里面涉及到一个新的事件:webContents的did-finish-load事件。对比一下熟知的jquery的话,苏南大叔认为,可能就是类似jq的$(function(){})的类似事件。
总结

正确理解了主进程和渲染进程的通信方式,才能更好的把控electron程序。当然,这些事件监听还有很多相关事件,比如once,remove之类的事件。不过,使用的概率相对较小。目前就不在本文的探讨范围内了。
当然,渲染进程之间相互发消息,而不经过主进程,也是可以的。
以上是 electron主进程和渲染进程通信 的全部内容, 来源链接: utcz.com/a/119172.html
