matt
matt

Reputation: 89

Cannot read property on of undefined. Electron BrowserWindow object

I am trying to learn Electron, but am running into an issue with the Pluralsight tutorial I am using. I installed the 'electron-prebuilt' module. I get an error everytime I run "npm start". The window opens as expected, but the error message that pops up in a dialog box kind of ruins the whole thing. Here is the error:

Uncaught Exception: TypeError: Cannot read property 'on' of undefined at Object.

There's more to the long error message but it won't let me copy and paste, and the rest of the error just refers to the location of the supposed problem on line 14 of my main.js code. Here is my main.js file:

const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

let mainWindow

app.on('ready', _ => {
  mainWindow = new BrowserWindow({
      height: 400,
      width: 400
  })
})

mainWindow.on('closed', _ => {
    console.log('closed')
    mainWindow = null
})

It's indicating that the BrowserWindow object I created doesn't have an "on" method, but I know this to be false per the Electron documentation:

https://electronjs.org/docs/api/browser-window

So I'm thinking that the value of mainWindow just isn't being set. I could try instantiating mainWindow with a new BrowserWindow object at the time I declare it, but I get an error message if I try that indicating that I can only instantiate BrowserWindow objects in ready functions.

Upvotes: 3

Views: 9226

Answers (2)

dlq
dlq

Reputation: 3219

This error also occurs if you are just calling node on your electron script instead of electron. Your npm start script should be calling npx electron . instead, so try running npx electron . or npx electron main.js first. See this relevant issue here:

https://github.com/electron/electron/issues/7475

Upvotes: 1

0.sh
0.sh

Reputation: 2762

you have to understand how callbacks work in node.js, callbacks are executed asynchronously, before app.onready fires, mainWindow is still undefined hence the declaration of let mainWindow assigns undefined to mainWindow, take mainWindow.on("closed", ....) into the app.on("ready") event handler. Do this

const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

let mainWindow

app.on('ready', _ => {
  mainWindow = new BrowserWindow({
      height: 400,
      width: 400
  })
  mainWindow.on('closed', _ => {
    console.log('closed')
    mainWindow = null
  })
})

Upvotes: 4

Related Questions