electron: "beforeunload" event doesn't work reliable

  • Electron version: 1.4.6
  • Operating system: Windows 10 (Version 1607)
function handleWindowBeforeunload(event) {
    const confirmed = (dialog.showMessageBox(remote.getCurrentWindow(), options) === 1);
    if (confirmed) {
        remote.getCurrentWindow().close();
    } else {
        event.returnValue = false;
    }
}

window.addEventListener("beforeunload", handleWindowBeforeunload);

Expected behavior

The window should stay open except when button 1 is pressed in the message box.

Actual behavior

Sometimes (~1 out of 10 times) the window will close, regardless of the button pressed in the message box. It happens more often when the developer tools are closed, and never happens when using the debugger to step over the code.

How to reproduce

Use the code snipped above with any message box with >= 2 buttons, with closed developer tools.

The code above is loosely modeled in the way atom does their beforeunload handling. (https://github.com/atom/atom/blob/master/src/window-event-handler.coffee#L150)

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 8
  • Comments: 22 (4 by maintainers)

Commits related to this issue

Most upvoted comments

I’ve found a workaround for this problem if someone is interested in that:

const {remote} = require('electron')
const {dialog} = remote

let closeWindow = false

window.addEventListener('beforeunload', evt => {
    if (closeWindow) return

    evt.returnValue = false

    setTimeout(() => {
        let result = dialog.showMessageBox({
            message: 'Quit app?',
            buttons: ['Yes', 'No']
        })

        if (result == 0) {
            closeWindow = true
            remote.getCurrentWindow().close()
        }
    })
})

This works for me on both Mac and Windows

$(window).on('beforeunload', function () {
  if (!confirm('Do you want to close screen?')) {
    return false;
  }
}

I am also experiencing the exact same problem. The issue starts to appear when you use dialog.showMessageBox(). Using event.returnValue = false; works every time.

@zcbenz Are you still unable to replicate this? Maybe I can put some time making a project that showcases the problem.