Electron启动报错:Cannot read properties of undefined (reading 'BrowserWindow')
Electron 23中渲染进程调用BrowserWindow报错:Cannot read properties of undefined (reading 'BrowserWindow')
问题原因
Electron 14及以上版本已移除内置的remote模块,你虽安装了@electron/remote包,但未在主进程中完成初始化配置,导致渲染进程无法访问remote对象,进而触发报错。
解决方案
1. 在主进程(main.js)中初始化@electron/remote
首先引入@electron/remote并完成初始化,同时为窗口启用远程调用功能:
const { app, BrowserWindow, Menu } = require('electron') const path = require('path'); const shell = require(`electron`).shell; const remoteMain = require('@electron/remote/main'); // 新增引入 // 初始化remote模块 remoteMain.initialize(); function createWindow() { const win = new BrowserWindow({ title: `Crypto Currency Page`, width: 800, height: 600, webPreferences: { preload: path.join(__dirname, './preload.js'), nodeIntegration: true, enableRemoteModule: true, contextIsolation: false, } }) remoteMain.enable(win.webContents); // 为当前窗口启用remote功能 win.webContents.openDevTools(); // ... 原有菜单、窗口加载逻辑不变 } // ... 原有app生命周期逻辑不变
2. 修改渲染进程(index.js)的BrowserWindow引入方式
替换原有的electron.remote调用,改为从@electron/remote直接引入:
const path = require('path'); const { BrowserWindow } = require('@electron/remote'); // 替换原引入方式 const notifyBtn = document.getElementById("notifyBtn"); notifyBtn.addEventListener(`click`, function () { const modalPath = path.join(`file://`, __dirname, `add.html`); let win = new BrowserWindow({ title: `Idk this page will load some day`, width: 400, height: 200, frame: false, webPreferences: { preload: path.join(__dirname, './preload.js'), enableRemoteModule: true, nodeIntegration: true, contextIsolation: false } }); win.on(`close`, function () { win = null }); win.loadURL(modalPath); win.show(); })
补充说明
你当前设置的nodeIntegration: true和contextIsolation: false虽能让渲染进程直接调用Node API,但不符合Electron安全最佳实践。后续建议改用preload脚本暴露必要API,避免直接开启全量Node集成。
内容的提问来源于stack exchange,提问作者AlexO
相关产品推荐
相关产品推荐

