系列文章目录
ipcMain模块的使用
前言
使用 ipcMain 模块进行主进程与渲染进程间通信
一、ipcMain 引入
在主进程中引入 ipcMain 模块
const {ipcMain} = require('electron');
在渲染进程中引入 ipcRenderer 模块
let {ipcRenderer} = require("electron");
二、使用步骤
1.html页面
代码如下(示例):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>💖 Hello World!</h1>
<p>Welcome to your Electron application.</p>
<!-- 点击开启新窗口 -->
<button id = "btn">点击创建新窗口</button>
<button id = "button" onclick="getProcess()">点击获取系统参数</button>
</body>
</html>
2.main.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)
})
// 监听渲染进程发送过来的 打开新窗口 事件
ipcMain.on("openNewwindow",(event,arg)=>{
cWindow("https://www.taobao.com")
cWindow("https://www.baidu.com")
})
if (require('electron-squirrel-startup')) {
eslint-disable-line global-require
app.quit();
}
const cWindow = (url) => {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences:{
// 浏览器 js 可以支持 node 接口
nodeIntegration: true,
contextIsolation:false
}
});
// 打开网络页面 loadURL
mainWindow.loadURL(url)
mainWindow.webContents.openDevTools();
};
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences:{
// 浏览器 js 可以支持 node 接口
nodeIntegration: true,
contextIsolation:false
}
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the DevTools.
mainWindow.webContents.openDevTools();
// 主动的发消息给渲染进程
setTimeout(()=>{
mainWindow.webContents.send("lc-active","创建窗口之后,主进程主动发送数据给渲染进程")
},2000)
};
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
该处使用的url网络请求的数据。
3. render.js代码
let {ipcRenderer} = require("electron");
// 监听渲染进程发送过来的 打开新窗口 事件
ipcRenderer.on("openNewindow",(event,arg)=>{
})
// 监听渲染进程发送过来的 lc-message 事件
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);
})
let btn = document.querySelector("#btn");
btn.onclick = function(){
ipcRenderer.send("openNewwindow");
}
function getProcess(){
// 获取 CPU 使用率
console.log("getCPUUsage",process.getCPUUsage());
// 获取环境参数
console.log("env",process.env);
// 获取windows系统位数
console.log("arch",process.arch);
// 获取系统版本
console.log("SystemVersion",process.getSystemVersion());
// 获取 electron 版本
console.log("version",process.version);
}
4. 实现效果
总结
ipcMain模块不仅用于主进程与渲染进程间通信,还可用于渲染进程与渲染进程间通信