关于electron:electron渲染进程与主进程互相通信

思路

  1. 主过程监听一个事件
  2. 渲染过程触发事件向主过程发送音讯
  3. 主过程收到渲染过程的音讯,给予渲染过程以响应
  4. 渲染过程收到主过程的响应

代码实现

主过程监听一个事件, 并且响应渲染过程
const {ipcMain} = require("electron")

ipcMain.on("sendMessage", (event, args) => {
  console.log("收到渲染过程的音讯",  args);
  win.webContents.send("receiveMessage", "我是主过程已收到音讯" + args); // 响应渲染过程
});
渲染过程触发主过程事件,并且监听主过程响应事件
<body>
    <button id="btn">发送告诉</button>
  </body>
<script>
    const { ipcRenderer } = require("electron");
    const oBtn = document.getElementById("btn");

    oBtn.onclick = function () {
        ipcRenderer.send("sendMessage", "我是渲染过程");
    };
    ipcRenderer.on('receiveMessage', (event, args)=>{
        console.log('接管到主过程的音讯',args)
    })
</script>

留神

  • 渲染过程须要汇合node过程,否者会报Uncaught ReferenceError: require is not defined谬误
const win = new BrowserWindow({
    // fullscreen: true,
    // transparent: true, // 窗口通明
    // frame: true, // 无边框
    // .......
    webPreferences: {
        nodeIntegration: true, // 汇合node过程
    },
});
  • 主过程console打出的中文乱码解决, start的时候加上chcp 65001
"scripts": {
   "start": "chcp 65001 && electron ."
},

残缺代码

  • 主过程
// index.js
const path = require("path");
const { app, BrowserWindow, ipcMain } = require("electron");

function createWindow() {
  // 创立浏览器窗口
  const win = new BrowserWindow({
    // fullscreen: true,
    // transparent: true, // 窗口通明
    // frame: true, // 无边框
    webPreferences: {
      nodeIntegration: true, // 汇合node过程
    },
  });

  win.loadFile("./app.html"); // 渲染过程网页

  ipcMain.on("sendMessage", (event, args) => {
    console.log("收到渲染过程的音讯",  args);
    win.webContents.send("receiveMessage", "我是主过程已收到音讯" + args);
  });
  win.webContents.openDevTools();  // 开启调试
}

app.whenReady().then(createWindow);
  • 渲染过程
<!--app.html-->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btn">发送告诉</button>
  </body>
  <script>
    const { ipcRenderer } = require("electron");
    const oBtn = document.getElementById("btn");

    oBtn.onclick = function () {
      ipcRenderer.send("sendMessage", "我是渲染过程");
    };
    ipcRenderer.on('receiveMessage', (event, args)=>{
        console.log('接管到主过程的音讯',args)
    })
  </script>
</html>

效果图

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理