深圳的天气骤降,还是挺冷的,大家要注意保暖。微信公众号:[猫十二的日常],欢迎留言和指出问题a
上次写了关于ipc通讯的一些方式,主要都是web页面向主进程通讯,主进程回复通讯,这个感觉和http有点相似,发送一个http资源的请求,服务返回一个资源结果,现在我们主要看这两个点
主进程主动推消息给web渲染进程的
web渲染进程之间的通讯
主进程向渲染进程主动通信
这个可能就牵扯到了一个比较重要的APi,BrowserWindow 这个是用于创建和控制浏览器窗口的,只能在主进程进行调用,当然也是这个家伙创建的渲染进程
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com')
const contents = win.webContents
console.log(contents)
这个创建之后返回的win下面的webContents就是可以渲染和控制web页面的api模块,咱们不会深入展开的,主要针对通讯讲一讲
contents.send(channel, …args)
channel
String 事件名称...args
any[] 传递的参数,和上节一样
目录准备,修改和删除都在这几个文件操作
my-electron-app/
├── package.json
├── main.js // 这个就是主进程
├── renderer.js // 这个就是渲染进程
└── index.html //web页面
index.html
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Electron演示title>head><body>
Electron演示<iframe src='./other.html'>iframe><script src="./renderer.js">script>body>html>
renderer.js
const { ipcRenderer } = require("electron");
ipcRenderer.on("message", (event, arg) => {
console.log("主进程老哥,主动推消息了:", arg);
});
main.js
const { app, BrowserWindow, ipcMain } = require("electron");
function createWindow() {
const win = new BrowserWindow({
width: 1920,
height: 1080,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
});
const contents = win.webContents;
contents.openDevTools(); //打开调试工具
win.loadFile("index.html");
contents.on("did-finish-load", () => {
//页面加载完成触发的回调函数
console.log("load");
contents.send("message", "我看到你加载完了,给你发个信息");
});
}
app.whenReady().then(createWindow);
app.on("window-all-closed",