Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix BrowserWindow is not a constructor error when creating child window in Electron renderer process

Tags:

I'm using electron to build an application that includes two windows. I'm trying to open a second window from inside renderer process doing something like:

const electron = require('electron'); const BrowserWindow = electron.BrowserWindow;  const childWindow = new BrowserWindow({    width: 800,    height: 600 }); 

I'm getting an error saying

BrowserWindow is not a constructor.

My other option is to use window.open, but that is not ideal since that returns BrowserWindowProxy object, which has limited functionality.

like image 503
Elena Filatova Avatar asked Aug 11 '17 16:08

Elena Filatova


2 Answers

I found that all I needed to do was to use the remote module. Electron doesn't allow to directly create a browser window from the renderer process, because it (BrowserWindow) requires ipc module to communicate with the main process. Electron documentation says:

In Electron, GUI-related modules (such as dialog, menu etc.) are only available in the main process, not in the renderer process. In order to use them from the renderer process, the ipc module is necessary to send inter-process messages to the main process.

So, new electron.BrowserWindow() doesn't work. However, using remote module correctly sets up inter-process communicating with the main process and the following modified code works for me:

const electron = require('electron');  const BrowserWindow = electron.remote.BrowserWindow;    const childWindow = new BrowserWindow({     width: 800,     height: 600  });

A more complete explanation of remote module is here: https://electron.atom.io/docs/api/remote/

like image 154
Elena Filatova Avatar answered Sep 23 '22 14:09

Elena Filatova


For anyone that also has this problem and their code isn't inside an electron renderer, you're probably running the script using node script.js, you need to run it using electron script.js.

like image 43
erik Avatar answered Sep 22 '22 14:09

erik