Tag Archives: electron Use remote Error

[Solved] electron Use remote Error: Cannot read properties of undefined (reading ‘BrowserWindow‘)

Recently, I wrote a small demo of remote while learning electron. There is such a code:

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

An error will be reported, as shown in the following figure:

Then I went to the Internet and looked at some articles. It seems to be a problem with the version. My electron is @V16.0.4, and remote abandoned the remote module in electron12, so we need to install the remote package ourselves.

1. First install the @electron/remote package under the project root directory:

npm install @electron/remote --save

2. Initialize in the main process:

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

3. And set enableremotemodule and contextisolation in the main process webpreferences:

 webPreferences: {
    nodeIntegration: true,
    contextIsolation: false,
    enableRemoteModule: true, // use remote module
 },

4. Set in the rendering process

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

Well, this is my overall Code:

Main process

var electron = require("electron");
var app = electron.app; // Reference app
var BrowserWindow = electron.
var mainWindow = null; // Specify the main window to open

// When electron has finished initializing and is ready to create a browser window
// This method is called
app.on("ready", () => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true, // use remote module
    },
  });

  require("@electron/remote/main").initialize(); // initialize
  require("@electron/remote/main").enable(mainWindow.webContents);
  mainWindow.loadFile("demo2.html"); // load the index.html page
  mainWindow.openDevTools(); // open developer tools

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

Subprocess

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;
    });
  };
};

Result display