ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

electron 使用remote 报错:Cannot read properties of undefined (reading ‘BrowserWindow‘)

2021-12-22 17:30:26  阅读:633  来源: 互联网

标签:remote undefined require BrowserWindow electron 报错 const mainWindow


最近在学习electron,写了一个remote的小demo,其中有这样一段代码:

const BrowserWindow = require("electron").remote.BrowserWindow;

会报错,如下图:

 

然后去网上找了一些文章看了看貌似是版本的问题,我用的electron是@v16.0.4, 而remote在electron12的时候废弃了remote模块,所以需要我们自己安装remote包。

1.  首先在项目根目录下安装@electron/remote包:

npm install @electron/remote --save

2. 在主进程中进行初始化:

require("@electron/remote/main").initialize();
require("@electron/remote/main").enable(mainWindow.webContents);

 3. 并在主进程webPreferences中设置enableRemoteModule和contextIsolation:

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

4. 在渲染进程中设置

const BrowserWindow = require("@electron/remote").BrowserWindow;

就好了,这是我整体的代码:

主进程

var electron = require("electron");
var app = electron.app; // 引用app
var BrowserWindow = electron.BrowserWindow; // 窗口引用
var mainWindow = null; // 申明要打开的主窗口

// 当electron完成了初始化并且准备创建浏览器窗口的时候
// 此方法被调用
app.on("ready", () => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true, // 使用remote模块
    },
  });

  require("@electron/remote/main").initialize(); // 初始化
  require("@electron/remote/main").enable(mainWindow.webContents);
  mainWindow.loadFile("demo2.html"); // 加载index.html 页面
  mainWindow.openDevTools(); // 打开开发者工具

  mainWindow.on("closed", () => {
    mainWindow = null;
  });
});

子进程

const btn = this.document.querySelector("#btn");
const BrowserWindow = require("@electron/remote").BrowserWindow;

window.onload = () => {
  btn.onclick = () => {
    newWin = new BrowserWindow({
      width: 500,
      height: 500,
    });

    newWin.loadFile("load.html");
    newWin.on("closed", () => {
      newWin = null;
    });
  };
};

结果展示

标签:remote,undefined,require,BrowserWindow,electron,报错,const,mainWindow
来源: https://blog.csdn.net/baixue0111/article/details/122088933

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有