You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron:通过contextBridge更新暴露的selfInfo并兼容旧代码

用contextBridge兼容原有window.electron.selfInfo的动态更新方案

contextBridge暴露到主世界的对象是被冻结的,无法直接修改其属性值,所以直接赋值更新selfInfo的方式行不通。要兼容原有window.electron.selfInfo的属性访问方式,你可以通过**访问器属性(getter)**实现动态获取最新值,具体方案如下:

基础实现(预加载脚本)

const { contextBridge, ipcRenderer } = require('electron');

// 维护内部状态变量,存储最新的selfInfo数据
let internalSelfInfo = null;

// 监听主进程的updateSelfInfo事件,更新内部状态
ipcRenderer.on('updateSelfInfo', (event, data) => {
  if (data) {
    // 与原逻辑对齐:如果data是完整的electron对象,取其中的selfInfo字段
    internalSelfInfo = data.selfInfo;
    // 如果原逻辑中data本身就是selfInfo数据,直接赋值:internalSelfInfo = data;
  }
});

// 通过contextBridge暴露对象,用getter实现动态取值
contextBridge.exposeInMainWorld('electron', {
  get selfInfo() {
    return internalSelfInfo;
  }
});

逻辑说明

  • 用内部变量internalSelfInfo存储最新数据,避开contextBridge对象不可修改的限制;
  • 暴露的electron.selfInfo是一个getter属性,前端每次访问window.electron.selfInfo时,都会实时返回internalSelfInfo的最新值;
  • 完全兼容原有前端代码,不需要修改任何window.electron.selfInfo的调用逻辑。

扩展:多动态属性场景

如果原逻辑中updateSelfInfo事件会更新多个属性,可维护一个完整的状态对象,逐个用getter暴露:

const { contextBridge, ipcRenderer } = require('electron');

let electronState = { selfInfo: null /* 其他初始属性 */ };

ipcRenderer.on('updateSelfInfo', (event, data) => {
  if (data) {
    // 合并更新状态,与原逻辑的{...data}行为一致
    electronState = { ...electronState, ...data };
  }
});

contextBridge.exposeInMainWorld('electron', {
  get selfInfo() {
    return electronState.selfInfo;
  },
  // 其他动态属性同理
  get userSettings() {
    return electronState.userSettings;
  }
});

内容的提问来源于stack exchange,提问作者Darren Chiang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 13:24:58