Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the 'before-quit' event in electron (atom-shell)

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!

like image 784
SKuijers Avatar asked Sep 16 '25 09:09

SKuijers


1 Answers

I had the same issue, this was my solution:

In renderer:

const { ipcRenderer } = require('electron')
window._saved = false
window.onbeforeunload = (e) => {
    if (!window.saved) {
        callSaveAPI(() => {
            // success? quit the app
            window._saved = true
            ipcRenderer.send('app_quit')
            window.onbeforeunload = null
        })
    }
    e.returnValue = false
}

In main:

const { ipcMain } = require('electron')
// listen the 'app_quit' event
ipcMain.on('app_quit', (event, info) => {
    app.quit()
})
like image 179
Jacket Chen Avatar answered Sep 19 '25 03:09

Jacket Chen