Reputation: 4104
I have an electron app that loads the URL of the web version of the app. However I cannot close the application by clicking in the X button and I dont have access to the webapp. I have tried this:
let count = BrowserWindow.getAllWindows().length;
///returns 1, so there is only 1 window)
window.onbeforeunload=function(e){
e.returnValue=undefined;
return undefined;
}
window.close();
app.quit();
Nothing happens.
app.exit(0)
works, but I dont want to use it. Is there a way I can close the app with window.close
and app.quit
?
EDIT: The problem are those global beforeunload events. If i click remove in the devtools I am able to close the app.
Also this let names= window.eventNames();
returns an array that does not have any beforeunload events
Upvotes: 4
Views: 8129
Reputation: 701
You need to save the BrowserWindow object reference. Then listen for a 'closed' event and dereference it:
const { app, BrowserWindow } = require('electron');
let win; // = new BrowserWindow();
win.on('closed', () => {
win = null
})
After dereference, it's all simple, just listen for 'window-all-closed' event on app:
app.on('window-all-closed', () => {
app.quit()
})
Upvotes: 1
Reputation: 344
In the file where you created the BrowserWindow, you can attach an event to the 'close' handler for the window. For Electron, this is usually main.js.
const {app, BrowserWindow} = require('electron');
let mainWindow = null;
app.on('ready', () => {
mainWindow = new BrowserWindow({
//options here
});
mainWindow.loadURL([url here]);
//attach event handler here
mainWindow.on("close", () => {
mainWindow = null;
app.quit();
});
});
For good measure, in the case that you may have more than one window, place this in your main.js file.
app.on('window-all-closed', () => {
if(process.platform !== "darwin")
app.quit();
});
Upvotes: 1