当前位置: 首页 > article >正文

electron中主进程和渲染进程通信3种方式【详细教程】

  • 1. 使用ipcMain和ipcRenderer
  • 2. 实验步骤
  • 3. 其他方法

1. 使用ipcMain和ipcRenderer

我们知道electron应用中main.js可以理解成主进程,index.html可以理解成渲染进程。两个进程间是通过 ipcMain 和 ipcRenderer 实现进程通信的。

文章配图

2. 实验步骤

  1. 创建项目结构
  • main.js:主进程脚本
  • preload.js:预加载脚本
  • index.html:渲染器进程的 HTML 文件
  • renderer.js:渲染器进程的 JavaScript 文件
  1. 编写主进程代码(main.js)
    在主进程中,使用 ipcMain 模块监听来自渲染器进程的消息,并进行处理。以下是一个简单的示例代码:

const { app, BrowserWindow, ipcMain } = require('electron');

const path = require('node:path');



function createWindow() {

  const mainWindow = new BrowserWindow({
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
    },
  });


  mainWindow.loadFile('index.html');


  // 监听来自渲染器进程的消息
  ipcMain.on('message-from-renderer', (event, message) => {
    console.log('主进程收到消息:', message);
    event.reply('reply-from-main', 'Hello from main process!');
  });
}



app.whenReady().then(createWindow);



app.on('window-all-closed', () => {

  if (process.platform !== 'darwin') app.quit();
});

  1. 编写预加载脚本(preload.js)
    使用 contextBridge 和 ipcRenderer 模块,将特定的 IPC 功能暴露给渲染器进程。这可以确保安全性和隔离性:

const { contextBridge, ipcRenderer } = require('electron');



contextBridge.exposeInMainWorld('api', {

  sendMessage: (message) => ipcRenderer.send('message-from-renderer', message),
  onReply: (callback) => ipcRenderer.on('reply-from-main', callback),
});

  1. 编写渲染器进程代码(index.html 和 renderer.js)
    在渲染器进程中,通过 preload.js 暴露的 API 发送消息到主进程,并接收回复。

index.html


<!DOCTYPE html>

<html>

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>IPC Communication</title>
  </head>
  <body>
    <h1>IPC Communication Example</h1>
    <button id="sendButton">Send Message to Main Process</button>
    <p id="replyMessage"></p>
    <script src="./renderer.js"></script>
  </body>
</html>

renderer.js


document.getElementById('sendButton').addEventListener('click', () => {

  window.api.sendMessage('Hello from renderer process!');
});



window.api.onReply((event, message) => {

  document.getElementById('replyMessage').innerText = `Reply from main process: ${message}`;
});

  1. 实验结果
    当点击页面上的按钮时,渲染器进程会通过 window.api.sendMessage 向主进程发送消息。

主进程接收到消息后,通过 event.reply 向渲染器进程发送回复。

渲染器进程通过 window.api.onReply 接收到回复,并在页面上显示。

文章配图

3. 其他方法

除了 ipcRenderer.send 和 ipcMain.on 进程通信外还有

ipcRenderer.invoke 和 ipcMain.handle

MessagePort这两种方法将在后面的博文中继续讨论。


http://www.kler.cn/a/540509.html

相关文章:

  • SpringSecurity高级用法
  • [ Spring ] Integrate Spring Boot Service Monitor Prometheus and Grafana
  • 基于机器学习的DDoS检测系统实战
  • 元宇宙中的隐私与数据保护:Facebook 的挑战与机遇
  • 跟我学C++高级篇——CRTP的高级应用
  • RestTemplate Https 证书访问错误
  • macOS 上部署 RAGFlow
  • 【Hadoop】大数据权限管理工具Ranger2.1.0编译
  • 在spring boot 项目中远程调用时,如果使用subList()方法报错原因分析
  • CNN-GRU卷积神经网络门控循环单元多变量多步预测,光伏功率预测(Matlab完整源码和数据)
  • python视频爬虫
  • 定制化APP:开启企业数字化转型新未来
  • 15 大 AWS 服务
  • 比亚迪发布智能化战略,天神之眼开创全民智驾
  • 工厂方法模式详解(Java)
  • Vue 和 React 的生态系统有哪些主要区别
  • Vue 和 React 在性能上的具体差异是什么
  • 服务器绑定 127.0.0.1 和 0.0.0.0 的区别
  • 大模型训练-gpu显卡训练环境搭建
  • ArcGIS Pro批量创建离线服务sd包
  • Kitchen Gadgets
  • Qt:项目文件解析
  • 海云安开发者智能助手(D10)全面接入DeepSeek,赋能开发者安全高效编码新范式
  • JavaScript特效大全:343个动态效果实例教程
  • 【信息系统项目管理师-案例真题】2017下半年案例分析答案和详解
  • 一键查看电脑各硬件详细信息 轻松查看电脑硬件参数