I am learning to write JavaScript in Electron. I have two windows. A main window and a child window. When the main window closes selecting the X on a windows computer I want it to close the entire app including the child window. The line below works on a Mac PC.
mainWindow.on('closed', () => app.quit());
What is the proper way of doing the same thing for windows pcs.
app.quit()
is the correct function for doing this.
Quote from the documentation (https://github.com/electron/electron/blob/master/docs/api/app.md)
Try to close all windows. The
before-quit
event will be emitted first. If all windows are successfully closed, thewill-quit
event will be emitted and by default the application will terminate.This method guarantees that all
beforeunload
and unload event handlers are correctly executed. It is possible that a window cancels the quitting by returningfalse
in thebeforeunload
event handler.
You could correct the behavior in Windows if you close the app directly on button click, instead of closing the window -> listening to the event -> and quitting the app
const app = require('electron').remote.app;
const close = document.getElementById('myCloseButton');
close.on('click',function(){
app.quit();
});
Note: app.exit()
also exists but it does not send the events mentioned above, so it should only be used if necessary.
I handle it like so within main.js:
// create two windows
let mainWindow = new BrowserWindow();
let backgroundWindow = new BrowserWindow();
Expose a function to the renderer (in this case "mainWindow") to shut down the app:
exports.closeAppWindow = function(){
backgroundWindow.close();
mainWindow.close();
}
As the quoted documentation above states:
If all windows are successfully closed, the will-quit event will be emitted and by default the application will terminate.
The app then shuts down since both windows have been closed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With