How to use the 'Before Quit' event on App


#1

I have a application which needs to make an API call before it quits (something like logout). As I still need access to some app data (redux store) for the API call so I decided to listen to the ‘before-quit’ event on app.

I tried the following code:

import {remote} from 'electron';
let loggedout = false;

remote.app.on('before-quit', (event) => {
  if (loggedout) return; // if we are logged out just quit.
  console.warn('users tries to quit');

  // prevent the default which should cancel the quit
  event.preventDefault();

  // in the place of the setTimout will be an API call
  setTimeout(() => {
    // if api call was a success
    if (true) {
      loggedout = true;
      remote.app.quit();
    } else {
      // tell the user log-out was not successfull. retry and quit after second try.
    }
  }, 1000);
});

The event never seems to fire or preventing shutdown does not work.
When I replace before-quit with browser-window-blur the event does fire and the code seems to work.

For reference I use Electron 1.2.8 (Due to some dependencies I cannot upgrade). I’ve double checked and before-quit event was already implemented in that version.

Any Ideas why this event does not seem to be fired?

Thanks in advance and happy holidays!


#2

Found a solution for this.

There are 2 problems which prevented the code from working:

  1. Somehow the ‘before-quit’ event does not fire in the rerender process. (not main.js).
  2. Once I moved the eventlistener into the main-process preventing the default did not stop the windows from closing. This can only be done through adding an window.onbeforeunload function which returns false. Like suggested in this thread.

One caveat is that the return statement of onbeforeunload does not get updated. In my case I first returned false (to prevent the closing of the window). The second time it did not return false but it kept preventing the closing of the window.

I got around that through overriding the window.onbeforeunload with a new function which did not return false.