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

  • [1. 使用ipcMain和ipcRenderer](#1. 使用ipcMain和ipcRenderer)
  • [2. 实验步骤](#2. 实验步骤)
  • [3. 其他方法](#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();
    });

  2. 编写预加载脚本(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),
    });

  3. 编写渲染器进程代码(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这两种方法将在后面的博文中继续讨论。

相关推荐
千叶寻-1 小时前
正则表达式
前端·javascript·后端·架构·正则表达式·node.js
記億揺晃着的那天8 小时前
Vue + Element UI 表格自适应高度如何做?
javascript·vue.js·ui
GISer_Jing9 小时前
ByteDance——jy真题
前端·javascript·面试
真的想不出名儿9 小时前
Vue 中 props 传递数据的坑
前端·javascript·vue.js
阳光阴郁大boy9 小时前
星座运势网站技术解析:从零打造现代化Web应用
前端·javascript
sorryhc9 小时前
如何设计一个架构良好的前端请求库?
前端·javascript·架构
Queen_sy9 小时前
vue3 el-date-picker 日期选择器校验规则-选择日期范围不能超过七天
javascript·vue.js·elementui
lvchaoq10 小时前
react 修复403页面无法在首页跳转问题
前端·javascript·react.js
郝开10 小时前
6. React useState基础使用:useState修改状态的规则;useState修改对象状态的规则
前端·javascript·react.js
技术钱11 小时前
react+andDesign+vite+ts从零搭建后台管理系统(三)-Layout布局
javascript·react.js·ecmascript