1:進(jìn)程間通信
進(jìn)程間通信使用 ipcMain與ipcRenderer模塊,參考:https://www.w3cschool.cn/electronmanual/electronmanual-ipc-main.html?; ? ? ?https://www.w3cschool.cn/electronmanual/electronmanual-ipc-renderer.html
在主進(jìn)程使用ipcMain:
const ipcMain =require('electron').ipcMain;
ipcMain.on('message',function(event, arg) {//監(jiān)聽(tīng)渲染進(jìn)程發(fā)送的message
????????console.log(arg);// prints "ping"
????????event.sender.send('reply','pong');//event.sender獲取事件的發(fā)送者,并發(fā)送reply事件舆蝴,‘pong’為發(fā)送的數(shù)據(jù)
});
渲染進(jìn)程ipcRenderer:
const ipcRenderer =require('electron').ipcRenderer;
ipcRenderer.sendSync('message','ping')//發(fā)送同步消息,send()異步
ipcRenderer.on('reply',function(event, arg) {console.log(arg);// prints "pong"});//監(jiān)聽(tīng)reply
在主進(jìn)程也可以使用以下方式發(fā)送消息:mainWindow.webContents.send('saveMessage','delect',index,innerIndex)
webContents從主進(jìn)程向渲染進(jìn)程發(fā)送消息题诵,查看更多?https://www.w3cschool.cn/electronmanual/electronmanual-web-contents.html?.
以下為webContents的send()官方使用介紹
webContents.send(channel[, arg1][, arg2][, ...])
channel?String
arg?(可選)
通過(guò)?channel?發(fā)送異步消息給渲染進(jìn)程须误,你也可發(fā)送任意的參數(shù).參數(shù)應(yīng)該在 JSON 內(nèi)部序列化,并且此后沒(méi)有函數(shù)或原形鏈被包括了.
渲染進(jìn)程可以通過(guò)使用?ipcRenderer?監(jiān)聽(tīng)?channel?來(lái)處理消息.
例子仇轻,從主進(jìn)程向渲染進(jìn)程發(fā)送消息 :
// 主進(jìn)程:
var window=null;
app.on('ready',function(){
????window=new BrowserWindow({width:800, height:600});
????window.loadURL('file://'+ __dirname +'/index.html');
? ? ? ?window.webContents.on('did-finish-load',function(){
????????????window.webContents.send('ping','whoooooooh!'); //主進(jìn)程發(fā)送消息ping
?????});
});
在渲染進(jìn)程:
require('electron').ipcRenderer.on('ping', function(event, message) {//監(jiān)聽(tīng)ping事件
? ? ? console.log(message);? // Prints "whoooooooh!"??
? });
2:使用webview控件加載頁(yè)面時(shí),webview所在頁(yè)面與被加載頁(yè)面間的通信
electron webview標(biāo)簽介紹:https://electronjs.org/docs/api/webview-tag
webview所有的方法必須在加載完成之后才能使用奶甘,如下:
webview所在頁(yè)面
const webview = document.querySelector('webview')
? ?webview.addEventListener('dom-ready', () => {
????? ????webview.openDevTools()
????})
使用send()方法發(fā)送消息webview.send('start') //發(fā)送start篷店,同上面的?wenContents的send()方法
在被webview加載的頁(yè)面里?
可以通過(guò)?ipcRenderer?模塊去監(jiān)聽(tīng)channel?事件,從而處理發(fā)過(guò)來(lái)的這些信息
const {ipcRenderer} = require('electron')
ipcRenderer.on('start', (ev) => {//監(jiān)聽(tīng)start
? ? ? ? ? ? console.log(ev)
? ? ? ? })
$('#sendBT').click(function() {
? ? ? ? ? ? ipcRenderer.sendToHost('ztree') //向webview所在頁(yè)面發(fā)送消息
? })
?注意://ipcRenderer.sendToHost(channel[, arg1][, arg2][, ...]),它的事件將發(fā)往 host page 的 webview 元素疲陕,而不是主進(jìn)程.
//在webview所在頁(yè)面使用?webview.addEventListener('ipc-message',(event)=>{})監(jiān)聽(tīng)被加載特免傳送的消息
webview.addEventListener('ipc-message', (event) => { //ipc-message監(jiān)聽(tīng)方淤,被webview加載頁(yè)面?zhèn)鱽?lái)的信息
? ? ? ? ? ? ? ? console.log(event.channel)
? ? ? ? ? ? })