上圖:
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)
})