electron 通信总结

默认开启上下文隔离的情况下

渲染进程调用主进程方法:

主进程

  1. 在 main.js 中, 使用 ipcMain.handle,添加要处理的主进程方法
    const { ipcMain } = require("electron");

  2. 在 electron 中创建 preload.ts 文件,从 electron 中引入的 contextBridge 桥接方法

    暴露全局变量 eleapi 到渲染进程。并添加要调用的主进程方法。通过 ipcRenderer.on/invoke方法调用主进程方法。

ts 复制代码
const { contextBridge, ipcRenderer } = require("electron");

contextBridge.exposeInMainWorld("eleapi", {
  mainNotifyCallback: (cb) => {
    ipcRenderer.on("mainNotify", cb);
  },
  tcpRevDataCallback: (cb) => {
    ipcRenderer.on("tcpRevData", cb);
  },
  tcpSndData: (data) => {
    ipcRenderer.invoke("tcpSendData", data);
  },
  ipccall: async (data) => await ipcRenderer.invoke('ipccall', data),
  getDebugConfig: async () => await ipcRenderer.invoke("getDebugConfig"),
  openWindow: (url) => {
    ipcRenderer.send("openWindow", url);
  }
});
  1. 在 main.js 创建窗口的方法中,预加载 preload.ts

渲染进程:

  1. 页面通过 window.eleapi.xxx访问暴露的方法。

主进程向渲染进程发送消息

preload文件中,通过 ipcRenderer.on("mainNotify", cb);监听到消息,向 web 派送 mainNotifyCallback

相关推荐
你好潘先生1 天前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
orion572 天前
Missing Semester Class1:course overview and introduction of shell
linux
用户120487221612 天前
Linux驱动编译与加载
linux·嵌入式
程序员老赵2 天前
服务器文件不想 SFTP 上传?Docker 跑个 File Browser,浏览器就能管理
服务器·docker·开源
vivo互联网技术2 天前
从 10 分钟到 1 秒:ES 深度分页任意跳页的三轮优化实战
服务器·数据库·redis·elasticsearch·深度分页
用户805533698032 天前
Input 子系统架构:Core、Handler、Driver 三层是怎么协作的
linux·嵌入式
用户805533698032 天前
RK-Forge外设系列开篇 - 把板子从「能启动」变成「能用」:Ethernet/SPI/MMC 三个纯接线外设
linux·github·嵌入式
七歌杜金房3 天前
我终于又有了自己的 Linux 电脑
linux·debian·mac
tntxia4 天前
linux curl命令详解_curl详解
linux