aleczandru
aleczandru

Reputation: 5449

OnBeforeUnload ajax request not working on IE8 a IE9

Hi I have been searching alot for a solution to be able to be able to send an ajax request when the user closes the browser.So far all I have found is the onBeforeUnload event.This is what I have so far:

$(window).bind('beforeunload', function () {
   $.ajax({
    type: 'GET',
    async: false,
    url: '/Home/Get/'
  });
});

and I have also tryed using the native javascript:

window.onbeforeunload = function (e) {
    $.ajax({
        type: 'GET',
        async: false,
        url: '/Home/Get/'
    });
};

Now my interesest is not to recieve back the callback I only want to be able to execute a method on the server side when the browser closes.

This seems to work reliable on chrome , firefox an IE10 , but it does not work on IE9 and IE8 at all.

Does anyone know a solution for this problem?

Upvotes: 0

Views: 1221

Answers (1)

Freedom
Freedom

Reputation: 833

You can try to use a synchronous request to do that.
Browsers may not wait an asynchronous request complete(or even established.) here is another similar question here, please refer to it.

but there is one thing you should care about is: when using synchronous ajax call, user's browser will be blocked until the ajax call complete. It's not good for the user experience. And even worse, if your some bug happened in your server and the ajax request can not complete, the browser will be not responding. so be careful to do this!

BTW, for a good design, the server should not rely on the ajax request sent by the client to do some clean-up job. If you have to do such a job, use some other techniques, such as implementing a heartbeat mechanism.

Upvotes: 2

Related Questions