Electron13.1.X及以上调用remote.getBrowserWindow报错如何解决?
问题根因
Electron 从v10版本开始默认禁用了内置remote模块,v14及以上版本更是直接将内置remote模块从核心库中移除,因此你在渲染进程中通过require('electron').remote获取到的值为undefined,调用方法时才会抛出属性读取错误。
另外你原有代码中的remote.getBrowserWindow()是方法名错误,正确的内置remote获取当前窗口方法为remote.getCurrentWindow(),低版本能运行大概率是你本地之前对remote做了自定义封装。
修复方案
方案1:替换为官方维护的@electron/remote包(适配原有代码逻辑)
- 安装依赖
npm install @electron/remote --save
- 修改主进程
main.js代码
const { app, Notification, ipcMain, BrowserWindow } = require('electron'); // 引入并初始化@electron/remote const remoteMain = require('@electron/remote/main'); remoteMain.initialize(); var Path = require('path'); var url = require('url'); // 创建窗口时添加相关配置 let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ // 你的原有窗口配置 webPreferences: { // 开启配置适配remote调用 nodeIntegration: true, contextIsolation: false, enableRemoteModule: true } }) // 给当前窗口启用remote能力 remoteMain.enable(mainWindow.webContents); // 你的原有窗口加载逻辑 } app.whenReady().then(createWindow) // 其余原有主进程逻辑保持不变
- 修改渲染进程
menuHandler.js代码
// 从新包引入remote const remote = require("@electron/remote"); // 调用正确方法获取当前窗口实例 const Window = remote.getCurrentWindow(); // 最小化逻辑保持不变 $("#minimize").click(function() { Window.minimize(); });
方案2:使用IPC通信实现(Electron官方推荐的安全方案,无需开启不安全配置)
该方案不需要引入remote相关依赖,也不需要开启nodeIntegration等降低安全性的配置,更符合Electron安全规范。
- 主进程
main.js新增监听逻辑
const { app, Notification, ipcMain, BrowserWindow } = require('electron'); var Path = require('path'); var url = require('url'); // 新增最小化事件监听 ipcMain.on('window-minimize', (event) => { const targetWindow = BrowserWindow.fromWebContents(event.sender); targetWindow.minimize(); }) // 其余原有主进程逻辑保持不变
- 修改渲染进程
menuHandler.js代码
const { ipcRenderer } = require("electron"); $("#minimize").click(function() { // 发送最小化指令给主进程 ipcRenderer.send('window-minimize'); });
内容的提问来源于stack exchange,提问作者Dale
相关产品推荐
相关产品推荐

