window.onbeforeunload ajax request in Chrome window.onbeforeunload ajax request in Chrome google-chrome google-chrome

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.


Checkout the Navigator.sendBeacon() method that has been built for this purpose.

The MDN page says:

The navigator.sendBeacon() method can be used to asynchronously transfer small HTTP data from the User Agent to a web server.

This method addresses the needs of analytics and diagnostics code that typically attempt to send data to a web server prior to the unloading of the document. Sending the data any sooner may result in a missed opportunity to gather data. However, ensuring that the data has been sent during the unloading of a document is something that has traditionally been difficult for developers.

This is a relatively newer API and doesn't seems to be supported by IE yet.