进程间通信使用 ipcMain与ipcRenderer模块,参考:https://www.w3cschool.cn/electronmanual/electronmanual-ipc-main.html ;
https://www.w3cschool.cn/electronmanual/electronmanual-ipc-renderer.html
在主进程使用ipcMain:
const ipcMain =require('electron').ipcMain;
ipcMain.on('message',function(event, arg) {//监听渲染进程发送的message
console.log(arg);// prints "ping"
event.sender.send('reply','pong');//event.sender获取事件的发送者,并发送reply事件,‘pong’为发送的数据
});
渲染进程ipcRenderer:
const ipcRenderer =require('electron').ipcRenderer;
ipcRenderer.sendSync('message','ping')//发送同步消息,send()异步
ipcRenderer.on('reply',function(event, arg) {console.log(arg);// prints "pong"});//监听reply
在主进程也可以使用以下方式发送消息:
mainWindow.webContents.send('saveMessage','delect',index,innerIndex)
webContents从主进程向渲染进程发送消息,查看更多 https://www.w3cschool.cn/electronmanual/electronmanual-web-contents.html .
以下为webContents的send()官方使用介绍
webContents.send(channel[, arg1][, arg2][, ...])
channel String
arg (可选)
通过 channel 发送异步消息给渲染进程,你也可发送任意的参数.参数应该在 JSON 内部序列化,并且此后没有函数或原形链被包括了.
渲染进程可以通过使用 ipcRenderer 监听 channel 来处理消息.
例子,从主进程向渲染进程发送消息 :
// 主进程:
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!'); //主进程发送消息ping
});
});
在渲染进程:
require('electron').ipcRenderer.on('ping', function(event, message) {//监听ping事件
console.log(message); // Prints "whoooooooh!"
});