Electron.js prevent windows close conditionally

I want to ask user if he really want to close an electron app.

Accordingly to docs - I've tried:

window.onbeforeunload = (e) => {
  const answer = confirm('Do you want to close the application?');
  e.returnValue = answer;
  if (answer) { window.close(); }
};

But my app still closes no matter what user choose. How to prevent close an Electron app conditionally?


I guess, I have an answer. It shouldn't be called in renderer process. Instead we should use mainWindow in main process for such operation and 'close' lifecycle method, which will be called right before closing.

this.mainWindow.on('close', (e) => {
  const choice = this.dialog.showMessageBox(
    this.mainWindow,
    {
      type: 'question',
      buttons: ['Yes', 'No, hang on', 'third option'],
      title: 'Confirm your actions',
      message: 'Do you really want to close the application?'
    }
  );
  console.log('CHOICE: ', choice);
  if (choice > 0) e.preventDefault();
});

choice const will return an answer from buttons array, so 'Yes' will be as confirm and for other options we can prevent actions.

NOTE: I've pasted with this. from my code, but, obviously mainWindow is your BrowserWindow instance and this.dialog is electron.dialog that imported from import electron from 'electron';