electron 使用 remote 模块 报错

2,216 阅读1分钟

electron 使用 remote 模块报错:

const { BrowserWindow } = require('electron').remote

Uncaught TypeError: Cannot destructure property 'BrowserWindow' of 'require(...).remote' as it is undefined.

设置 enableRemoteModule: true,并不生效。

 webPreferences: {
       
        nodeIntegration: true,
        nodeIntegrationInWorker: true,
        nodeIntegrationInSubFrames: true,
        contextIsolation: false,
        enableRemoteModule: true,  // 使用remote模块
        webviewTag: true
      }

原因:Electron 14+ 已经移除remote模块

屏幕快照 2021-12-10 下午2.42.11.png

屏幕快照 2021-12-10 下午2.44.22.png

具体可看这里

解决:

  • 安装
npm install --save @electron/remote
  • main.js
// 引入
const remote = require('@electron/remote/main')

// 初始化 
remote.initialize()

// 允许窗口的 webcontents 访问
remote.enable(mainWindow.webContents)

  • renderer.js
const { BrowserWindow, app } = require('@electron/remote')