Cannot prevent window close in electron

Here is how you can prevent the closing:

after lots of trials I came up with a solution:

// Prevent Closing when work is running
window.onbeforeunload = (e) => {
  e.returnValue = false;  // this will *prevent* the closing no matter what value is passed

  if(confirm('Do you really want to close the application?')) { 
    win.destroy();  // this will bypass onbeforeunload and close the app
  }  
};

Found in docs: event-close and destroy


It is not possible, because processes opening the browser window is a renderer process, it is invoked via electron.remote, and therefore processed async. Because of this, the window is closed before the close event is processed. In case the process opening the browserwindow was the main process, then it would be fine.

This shows the case: https://github.com/CThuleHansen/windowHide And here is a longer discussion of the issue: https://discuss.atom.io/t/close-event-for-window-being-fired-after-window-has-been-closed/37863/4


In Electron ^15, do:

win.on('close', async e => {
  e.preventDefault()

  const { response } = await dialog.showMessageBox(win, {
    type: 'question',
    title: '  Confirm  ',
    message: 'Are you sure that you want to close this window?',
    buttons: ['Yes', 'No'],
  })

  response === 0 && win.destroy()
})