8

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.

3
  • So you're saying that doesn't work on Windows? What happens instead? Any errors or other feedback?
    – jonrsharpe
    Jun 16, 2017 at 12:30
  • When you hit the X on the main window the child window stays Jun 16, 2017 at 12:32
  • only if i actually select quit in my file menu does it actually close both. Jun 16, 2017 at 12:32

2 Answers 2

13

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, the will-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 returning false in the beforeunload 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.

1
  • It is possible that a window cancels the quitting by returning false in the beforeunload event handler. How can I override the beforeUnload events of all windows, so they cannot cancel?
    – kkica
    Jul 10, 2019 at 17:21
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.