Search code examples
javascriptfirefoxonbeforeunload

Why does FireFox window.onbeforeunload() only fire when a confirmation dialog is displayed?


If I register a Listener for 'onbeforeunload' console output will only be logged if a confirmation dialog box is displayed.

//Works

window.onbeforeunload = function(e) { 
    console.log('onbeforeunload');
    return 'a string';
}

However, remove "return 'a string';" and the console statement will not be displayed.

//Fails

window.onbeforeunload = function(e) { 
    console.log('onbeforeunload');
}

How can I record the event occurred without displaying a confirmation dialog to the user? This works in Chrome.


Solution

  • The string is always being logged, it's just that without a confirmation dialog, the browser is navigating to the new page (or reloading) and clearing the log.

    You can use the Enable persistent logs setting to preserve the message: https://developer.mozilla.org/en-US/docs/Tools/Settings