window.onbeforeunload in Chrome: what is the most recent fix?

Answer:

$(window).on('beforeunload', function() {
    var x =logout();
    return x;
});
function logout(){
        jQuery.ajax({
        });
        return 1+3;
}

A little mix and match, but it worked for me. The 1+3 makes sure that the logout function is being called (you'll see 4 if it's successful on the popup when you try to leave).


As of 69.0.3497.92, Chrome has not met the standard. However, there is a bug report filed, and a review is in progress.

  • Chrome requires returnValue to be set by reference to the event object, not the value returned by the handler.
  • The standard states that prompting can be controlled by canceling the event or setting the return value to a non-null value.
  • The standard states that authors should use Event.preventDefault() instead of returnValue.
  • The standard states that the message shown to the user is not customizable.

window.addEventListener('beforeunload', function (e) {
    // Cancel the event as stated by the standard.
    e.preventDefault();
    // Chrome requires returnValue to be set.
    e.returnValue = '';
});
    
window.location = 'about:blank';

Here's a more straightforward approach.

$(window).on('beforeunload', function() {
    return "You should keep this page open.";
});

The returned message can be anything you want, including the empty string if you have nothing to add to the message that Chrome already shows. The result looks like this:

enter image description here


According to MDN,

The function should assign a string value to the returnValue property of the Event object and return the same string.

This is the following

window.addEventListener( 'beforeunload', function(ev) { 
    return ev.returnValue = 'My reason';
})

This solved my problem why it wasn't working in my app:

Note that the user must interact with the page somehow (clicking somewhere) before closing its window, otherwise beforeunload is ignored in order not prevent abuse.