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

相关推荐
轻松Ai享生活1 天前
5 节课深入学习Linux Cgroups
linux
christine-rr1 天前
linux常用命令(4)——压缩命令
linux·服务器·redis
三坛海会大神5551 天前
LVS与Keepalived详解(二)LVS负载均衡实现实操
linux·负载均衡·lvs
東雪蓮☆1 天前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
乌萨奇也要立志学C++1 天前
【Linux】进程概念(二):进程查看与 fork 初探
linux·运维·服务器
_AaronWong1 天前
实现 Electron 资源下载与更新:实时进度监控
前端·electron
alphageek81 天前
Electron开源库入门教程:跨平台桌面应用框架
javascript·其他·electron·开源
绿箭柠檬茶1 天前
Ubuntu 服务器配置转发网络访问
服务器·网络·ubuntu
獭.獭.1 天前
Linux -- 信号【上】
linux·运维·服务器
hashiqimiya1 天前
centos配置环境变量jdk
linux·运维·centos