有时候我们想在渲染进程中通过一个事件去执行主进程里面的方法。或者在渲染进程中通知
主进程处理事件,主进程处理完成后广播一个事件让渲染进程去处理一些事情。这个时候就
用到了主进程和渲染进程之间的相互通信
ipcMain:当在主进程中使用时,它处理从渲染器进程(网页)发送出来的异步和同步信息,
当然也有可能从主进程向渲染进程发送消息。
ipcRenderer: 使用它提供的一些方法从渲染进程 (web 页面) 发送同步或异步的消息到主
进程。 也可以接收主进程回复的消息。
异步通信
渲染进程中的代码html
<button id="btn">发送通知</button>
渲染进程中代码js
const { ipcRenderer } = require("electron");
const oBtn = document.getElementById("btn");
oBtn.onclick = function() {
ipcRenderer.send("sendMessage","this is render");
}
主进程中监听事件
const { ipcMain } = require("electron");
ipcMain.on("sendMessage",(event,data) => {
console.log(data);
})
执行后的结果
this is render
渲染进程与主进程通信后主进程作出响应
渲染进程中的代码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="./render/ipcRender.js"></script>
</html>
渲染进程中的js代码
const { ipcRenderer } = require("electron");
const oBtn = document.getElementById("btn");
oBtn.onclick = function() {
ipcRenderer.send("sendMessage","this is renderer");
}
ipcRenderer.on("sendMain",(event,data) => {
console.log(data);
})
主进程的代码
const { ipcMain } = require("electron");
ipcMain.on("sendMessage",(event,data) => {
console.log(data);
event.sender.send("sendMain","this is a main")
})
执行的的结果
this is rendere
this is a main
同步方式通信
渲染进程中的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="./render/ipcRender.js"></script>
</html>
渲染进程中的js代码
const { ipcRenderer } = require("electron");
const oBtn = document.getElementById("btn");
oBtn.onclick = function() {
let res = ipcRenderer.sendSync("sendMessage","this is renderer");
console.log(res)
}
主进程中的js代码
const { ipcMain } = require("electron");
ipcMain.on("sendMessage",(event,data) => {
console.log(data);
event.returnValue = "this is main"
})
执行后的结果
this is renderer
this is main
附上main中的 js代码
const path = require("path");
const electron = require("electron");
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
let mainWindow = null;
app.on("ready",() => {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
// icon:'web/images/favicon-32x32.png',
resizable: true,
frame: true,
show: true,
backgroundColor: 'pink',
webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadFile("index.html")
mainWindow.webContents.openDevTools();
mainWindow.on("close",() => {
mainWindow = null;
})
mainWindow.show()
require("./main/ipcMain")
});
require("./main/shortcart")
app.on("window-all-closed",() => {
if(process.platform !== "darwin") {
app.quit()
}
})