进程模型、进程间通信 与Node 模块使用
进程模型、进程间通信 与Node 模块使用
进程模型
每个
主进程主要工作就是 控制应用程序生命周期 和 管理窗口、菜单、托盘等 ,另外主进程运行在
早期版本的
进程间通讯
上面内容中可以知道默认情况下渲染进程只能使用前端的语法规则,所以它和相当于后台的主进程间只能通过
不安全方式
上一章内容中有说到早期版本的
下面是个简单的例子,分别改写
const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");
function createWindow() {
const mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true, // 启用node环境
contextIsolation: false, // 禁用上下文隔离
},
});
mainWindow.loadFile("index.html");
mainWindow.webContents.openDevTools();
setInterval(() => {
// 使用下面方法向mainWindow发送消息,消息事件名称为 main-send ,内容为 hello
mainWindow.webContents.send("main-send", "hello");
}, 5000);
}
// 使用ipcMain.on方法监听 renderer-send 事件
ipcMain.on("renderer-send", (event, arg) => {
console.log(arg);
// 使用下面方法对产生事件的对象进行应答,应答时事件名为main-reply,内容为pong
event.reply("main-reply", "pong");
});
app.whenReady().then(() => {
createWindow();
app.on("activate", function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on("window-all-closed", function () {
if (process.platform !== "darwin") app.quit();
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>test</title>
</head>
<body>
<h1 id="txt">Hello World!</h1>
<script>
// 渲染进程使用ipcRenderer模块
const { ipcRenderer } = require("electron");
// 使用ipcRenderer.send方法发送消息,消息事件名称为 renderer-send ,内容为 ping
setInterval(() => {
ipcRenderer.send("renderer-send", "ping");
}, 3000);
// 使用ipcRenderer.on方法监听 main-reply 事件
ipcRenderer.on("main-reply", (event, arg) => {
console.log(arg);
});
// 使用ipcRenderer.on方法监听 main-send 事件
ipcRenderer.on("main-send", (event, arg) => {
console.log(arg);
});
</script>
</body>
</html>
上面就是个简单的通讯演示了,通过设置
主线程中可以使用
预加载方式
上面的方式
const { contextBridge, ipcRenderer } = require("electron");
// 使用contextBridge.exposeInMainWorld()方法将
// Function、String、Number、Array、Boolean、对象等
// 传递给渲染进程的window对象
contextBridge.exposeInMainWorld("myAPI", () => {
setInterval(() => {
ipcRenderer.send("renderer-send", "ping");
}, 3000);
ipcRenderer.on("main-reply", (event, arg) => {
console.log(arg);
});
ipcRenderer.on("main-send", (event, arg) => {
console.log(arg);
});
});
分别改写
// main.js中只需要改写下面内容就行了
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, "preload.js"), // 使用预加载脚本
},
});
<!-- index.html中只要改写下面内容就好了 -->
<script>
window.myAPI();
</script>
上面就是个简单的预加载的使用方式了,可以看到从使用角度来说其实也没太大差别,无非就是使用