electron例子 | 主进程和渲染进程通信
上图:
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button id="btn">同步发送消息</button> </body> <script type="text/javascript" src="./renderer.js"></script> </html>
index.js
const {app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
//监听渲染进程发送过来的lc-message事件
ipcMain.on('lc-message',(event,arg) => {
event.reply('lc-reply',"这是主进程的答复")
console.log(arg)
})
app.on("ready",() => {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
resizable: true,
frame: true,
show: true,
backgroundColor: 'pink',
webPreferences: {
nodeIntegration: true,
// 开启node
contextIsolation: false,
// 开启remote
enableRemoteModule:true
}
});
mainWindow.loadFile("index.html")
//打开控制面板
mainWindow.webContents.openDevTools();
//主进程主动发送消息
setTimeout(() =>{
mainWindow.webContents.send('lc-active',"创建窗口之后,主进程主动发送数据到渲染进程")
}, 2000)
});
app.on("window-all-closed",() => {
if(process.platform !== "darwin") {
app.quit()
}
})
renderer.js
const { ipcRenderer } = require("electron");
ipcRenderer.on('lc-active',(event, arg) =>{
console.log(event);
console.log(arg);
})
//主动发消息给主进程
ipcRenderer.send('lc-message', "子进程主动发送消息")
//监听主进程的回复
ipcRenderer.on('lc-reply',(event,arg)=>{
console.log(event)
console.log(arg)
})