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

相关推荐
Flash.kkl7 小时前
Linux——进程信号
运维·服务器
苏宸啊8 小时前
Linux权限
linux·运维·服务器
我是小疯子669 小时前
Python变量赋值陷阱:浅拷贝VS深拷贝
java·服务器·数据库
xqhoj9 小时前
Linux——make、makefile
linux·运维·服务器
张童瑶9 小时前
Linux 在线安装编译Python3.11
linux·运维·python3.11
Shi_haoliu9 小时前
SolidTime 在 Rocky Linux 9.5 上的完整部署流程
linux·运维·nginx·postgresql·vue·php·laravel
lifejump9 小时前
Pikachu | XXE
服务器·web安全·网络安全·安全性测试
Lkygo10 小时前
LlamaIndex使用指南
linux·开发语言·python·llama
qq_2546177710 小时前
nslookup 这个命令解析dns,和系统接口gethostbyname解析区别在哪?
linux·网络
Arwen30310 小时前
IP地址证书的常见问题有哪些?有没有特殊渠道可以申请免费IP证书?
服务器·网络·网络协议·tcp/ip·http·https