解决 Electron 报错 Unable to load preload script contextBridge 修复
排查 在 Electron 应用启动 BrowserWindow 时控制台报错 Unable to load preload script 或 contextBridge.exposeInMainWorld fails with symbol not found,分析 preload 路径解析与安全上下文隔离。
问题现象
Electron 为了防范远程渲染进程执行任意系统级 Node.js API 带来的严重提权风险,默认启用了 contextIsolation: true 和 nodeIntegration: false。开发者通过 preload.js 预加载脚本借助 contextBridge.exposeInMainWorld 将受控的通信桥暴露给前端渲染进程。但若路径拼接错误或打包后相对路径失效,应用启动时立即报出 Unable to load preload script: ...,前端 window.electronAPI 彻底为 undefined,页面交互全面瘫痪。
排查分析
检查创建 BrowserWindow 时的 webPreferences 配置
查看 main.js:
const mainWindow = new BrowserWindow({
webPreferences: {
// 常见失误:使用了相对路径,打包 ASAR 后解析定位失败
preload: './preload.js',
contextIsolation: true,
},
});
检查终端主进程输出的加载失败错误堆栈
确认是找不到物理文件 ERR_FILE_NOT_FOUND 还是执行脚本时内部语法报错;
在渲染进程控制台打印 window.electronAPI
确认对象是否成功挂载。
触发根因
preload路径未通过path.join(__dirname, 'preload.js')构建绝对路径,在生产打包为 ASAR 归档文件后无法找到对应资源;- 在
preload.js中引入了未被打包到依赖中的外部模块; - 暴露给
contextBridge.exposeInMainWorld的对象中包含了函数原型链、类实例或不可序列化符号导致安全策略拦截。
解决步骤
使用 path.join(__dirname, ...) 安全构建 preload 绝对物理路径
重构主进程窗口创建代码:
const path = require('path');
const mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
},
});
规范编写 preload.js 安全暴露 API
通过 contextBridge 封装调用:
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
sendMessage: (channel, data) => {
const validChannels = ['toMain'];
if (validChannels.includes(channel)) ipcRenderer.send(channel, data);
},
onReceive: (channel, func) => {
ipcRenderer.on(channel, (event, ...args) => func(...args));
},
});
检查 Electron-builder 打包配置文件确保 preload.js 被纳入 files 名单
防止打包漏传。
验证确认
重新打包并启动 Electron 桌面应用:
预加载脚本毫秒级平稳注入,渲染进程顺畅调用安全暴露的原生能力,报错彻底解决。


