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

Electron中如何在静态文件中获取应用版本号?

问题原因与解决方案

问题原因

当你同时开启NodeIntegration和ContextIsolation时,渲染进程的JavaScript上下文和主进程是完全隔离的。即使允许Node.js集成,渲染进程也无法直接访问electron.app这类Electron主进程API——ContextIsolation会把Electron的核心API和渲染进程的全局环境隔离开,这是Electron为了安全设计的机制,避免不可信的前端代码获取到高权限API。

解决方案

方法一:使用预加载脚本(推荐,符合安全规范)

预加载脚本运行在特殊上下文里,既可以访问Node.js和Electron API,又能通过contextBridge安全地向渲染进程暴露指定内容。

  1. 创建预加载脚本(比如preload.js):
const { contextBridge, app } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  getAppVersion: () => app.getVersion()
});
  1. 在创建BrowserWindow时配置预加载脚本:
const mainWindow = new BrowserWindow({
  // 其他窗口配置
  webPreferences: {
    nodeIntegration: true,
    contextIsolation: true,
    preload: path.join(__dirname, 'preload.js') // 确保路径正确
  }
});
  1. 在静态页面脚本中调用暴露的方法:
document.getElementById("releasever").textContent = "Release:" + window.electronAPI.getAppVersion();

注:段落标签需用textContent或innerHTML设置内容,而非content属性。

方法二:关闭ContextIsolation(不推荐,存在安全风险)

如果你的应用无需考虑不可信内容的安全问题,可以关闭ContextIsolation,让渲染进程直接访问Electron API:

修改窗口配置:

const mainWindow = new BrowserWindow({
  webPreferences: {
    nodeIntegration: true,
    contextIsolation: false // 关闭隔离
  }
});

页面脚本可直接使用:

document.getElementById("releasever").textContent = "Release:" + require('electron').app.getVersion();

但这种方式会让渲染进程拥有完整的Node.js和Electron API访问权限,若页面加载不可信资源,可能引发安全漏洞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:40:07