window.onbeforeunload ajax request in Chrome

This is relevant for newer versions of Chrome.

Like @Garry English said, sending an async request during page onunload will not work, as the browser will kill the thread before sending the request. Sending a sync request should work though.

This was right until version 29 of Chrome, but on Chrome V 30 it suddenly stopped working as stated here.

It appears that the only way of doing this today is by using the onbeforeunload event as suggested here.

BUT NOTE: other browsers will not let you send Ajax requests in the onbeforeunload event at all. so what you will have to do is perform the action in both unload and beforeunload, and check whether it had already taken place.

Something like this:

var _wasPageCleanedUp = false;
function pageCleanup()
{
    if (!_wasPageCleanedUp)
    {
        $.ajax({
            type: 'GET',
            async: false,
            url: 'SomeUrl.com/PageCleanup?id=123',
            success: function ()
            {
                _wasPageCleanedUp = true;
            }
        });
    }
}


$(window).on('beforeunload', function ()
{
    //this will work only for Chrome
    pageCleanup();
});

$(window).on("unload", function ()
{
    //this will work for other browsers
    pageCleanup();
});

I was having the same problem, where Chrome was not sending the AJAX request to the server in the window.unload event.

I was only able to get it to work if the request was synchronous. I was able to do this with Jquery and setting the async property to false:

$(window).unload(function () {
   $.ajax({
     type: 'GET',
     async: false,
     url: 'SomeUrl.com?id=123'
   });
});

The above code is working for me in IE9, Chrome 19.0.1084.52 m, and Firefox 12.