electronshoppinglist
electronshoppinglist copied to clipboard
TypeError: Cannot read propert 'on' of undefined.
This happened when I had to close all other windows when we close the main window. Couldn't find a solution to this. The error is for mainWindow.on("closed", function () { app.quit(); });
Below is my code.
const electron = require("electron");
const url = require("url");
const path = require("path");
const { app, BrowserWindow, Menu } = electron;
let mainWindow;
let addWindow;
//Listen for app to be ready
app.on("ready", function () {
//Create new window
mainwindow = new BrowserWindow({});
//Load the html file
mainwindow.loadURL(
url.format({
pathname: path.join(__dirname, "mainWindow.html"),
protocol: "file:",
slashes: true,
})
);
// Quit app when closed
mainWindow.on("closed", function () {
app.quit();
});
//Build the menu from template
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
//Insert the menu
Menu.setApplicationMenu(mainMenu);
});
//Handle create add window
function createAddWindow() {
addWindow = new BrowserWindow({
width: 300,
height: 200,
title: "Add shopping list item",
});
//Load the html file
addWindow.loadURL(
url.format({
pathname: path.join(__dirname, "addWindow.html"),
protocol: "file:",
slashes: true,
})
);
}
//Create menu template
const mainMenuTemplate = [
{
label: "File",
submenu: [
{
label: "Add Item",
click() {
createAddWindow();
},
},
{
label: "Clear Items",
},
{
label: "Quit",
accelerator: process.platform == "darwin" ? "Command+Q" : "Ctrl+Q",
click() {
app.quit();
},
},
],
},
];
@omwalhekar try to read text of your error: TypeError: Cannot read property 'on' of undefined. it means that something that stands before the 'on' method is indefinite. and indeed there is no 'mainwindow', I see only 'mainwindow'