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

varatis picture varatis · Mar 8, 2012 · Viewed 59.8k times · Source

Obviously, window.onbeforeunload has encountered its fair share of problems with Chrome as I've seen from all the problems I've encountered. What's the most recent work around?

The only thing I've got even close to working is this:

window.onbeforeunload = function () { return "alert" };

However, if I substitute return "alert" with something like alert("blah"), I get nothing from Chrome.

I saw in this question that Google purposefully blocks this. Good for them... but what if I want to make an AJAX call when someone closes the window? In my case, I want to know when someone has left the chatroom on my website, signalled by the window closing.

I want to know if there's a way to either
(a): fix the window.onbeforeunload call so that I can put AJAX in there
or
(b): get some other way of determining that a window has closed in Chrome

Answer

varatis picture varatis · Mar 9, 2012

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).