Electron预加载脚本无法正常运行,求解决方案
问题分析与解决
核心问题拆解
1. 主进程错误访问渲染进程变量
main.js中的console.log(versions)完全错误——versions是通过contextBridge暴露给渲染进程的全局变量,主进程(main.js运行环境)根本无法直接访问,这就是你看到ReferenceError: versions is not defined的原因,直接删除该语句即可。
2. webPreferences配置语法错误
你在BrowserWindow配置中把webPreferences写成了({ ... }),多余的括号会导致配置未被Electron正确识别,预加载脚本因此未被加载。
3. 版本属性路径错误
预加载脚本中写的process.version.node是错误的,Node.js、Chrome、Electron的版本信息实际存储在process.versions对象下,这是渲染进程获取到undefined的关键原因。
4. 冲突的渲染进程隔离配置
开启nodeIntegration: true会破坏contextBridge的隔离机制,Electron 12+版本中contextIsolation默认开启,两者同时使用会导致contextBridge无法正常工作,必须关闭nodeIntegration。
修正后的完整代码
main.js
const {app, BrowserWindow} = require('electron'); const path = require('path'); let mainWindow; const createWindow = () => { mainWindow = new BrowserWindow({ show: false, autoHideMenuBar: true, webPreferences: { // 修正语法错误,移除多余括号 preload: path.join(__dirname, 'scripts', 'preload.js'), nodeIntegration: false, // 必须关闭,配合contextBridge使用 contextIsolation: true, // 默认开启,显式声明更清晰 }, }); mainWindow.maximize(); mainWindow.show(); mainWindow.loadFile('index.html'); // 打开开发者工具,方便调试渲染进程 mainWindow.webContents.openDevTools(); } // 补充Electron窗口生命周期处理 app.whenReady().then(createWindow); app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); }); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
preload.js
const {contextBridge} = require('electron'); contextBridge.exposeInMainWorld('versions', { node: () => process.versions.node, chrome: () => process.versions.chrome, electron: () => process.versions.electron, });
render.js
const information = document.getElementById('info'); information.innerText = `This app is using Chrome (v${window.versions.chrome()}), Node.js (v${window.versions.node()}), and Electron (v${window.versions.electron()})`;
额外检查项
- 确认
preload.js的路径正确:path.join(__dirname, 'scripts', 'preload.js')对应项目根目录下的scripts/preload.js,若文件结构不同需调整路径。 - 查看渲染进程控制台(开发者工具),确认是否有路径错误、语法错误等提示。
- 确保使用的Electron版本支持
contextBridge(Electron 12+,推荐最新稳定版)。
内容的提问来源于stack exchange,提问作者proshanto-c
相关产品推荐
相关产品推荐

