Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing all app windows when using Electron

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.

like image 838
David Brierton Avatar asked Dec 10 '22 11:12

David Brierton


2 Answers

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.

like image 148
Hans Koch Avatar answered Dec 26 '22 23:12

Hans Koch


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.

like image 37
user1990962 Avatar answered Dec 27 '22 00:12

user1990962