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这两种方法将在后面的博文中继续讨论。

相关推荐
T***u33323 分钟前
JavaScript在Node.js中的流处理大
开发语言·javascript·node.js
Croa-vo41 分钟前
TikTok 数据工程师三轮 VO 超详细面经:技术深挖 + 建模推导 + 压力测试全记录
javascript·数据结构·经验分享·算法·面试
艾小码2 小时前
还在为组件通信头疼?defineExpose让你彻底告别传值烦恼
前端·javascript·vue.js
槁***耿2 小时前
TypeScript类型推断
前端·javascript·typescript
y***54882 小时前
TypeScript在React项目中的状态管理
javascript·react.js·typescript
全马必破三4 小时前
CSS 和 JS 如何阻塞浏览器渲染 DOM
javascript
c***V3235 小时前
Vue优化
前端·javascript·vue.js
努力往上爬de蜗牛6 小时前
react native真机调试
javascript·react native·react.js
y***86697 小时前
TypeScript在Electron应用中的使用
javascript·typescript·electron
zy happy9 小时前
若依 vue3 报错:找不到模块“@/api/xxxx/xxxxx”或其相应的类型声明。。Vue 3 can not find mod
前端·javascript·vue.js