jaypabs
jaypabs

Reputation: 1567

onBeforeUnload with ajax does not work with IE

I'm just wondering why this is not working with IE. It works fine with Chrome and Firefox.

    window.onbeforeunload = function()
{
    fetch("http://"+window.location.hostname+"/process_sc.php?cC=" + 1);
} 

function fetch(url) {
    var x = (window.ActiveXObject) ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
    x.open("GET", url, false);
    x.send(null);
}   

Upvotes: 1

Views: 3048

Answers (2)

haui
haui

Reputation: 617

The problem is that you use a GET instead of a POST request. The browser may use a cached result from the very first request.

This explains the fact that "it works only on the first time I open IE" as written as in response to another answer.

By the way, the AJAX call in onunload seems to work reliably in IE10 only if you use the parameter async = false in XMLHttpRequest.open(...), which you already did.

Upvotes: 1

WTK
WTK

Reputation: 16971

How can you tell it isn't working?

In general, there's little time between beforeunload event, unload event and actual page exit. At page unload all running scripts are dropped (browser than closes the window or navigates to address provided by user for example).

What might be happening here is browser doesn't really have time to send ajax request before page is unloaded.

I've seen couple of ways to ensure your final request before page unload will be completed. One of them is sending request and then introducing loop that is running for X number of miliseconds, postponing unload event and ensuring ajax request can be completed.

window.onbeforeunload = function() {
    fetch("http://"+window.location.hostname+"/process_sc.php?cC=" + 1);
    // here we force browser to wait for 300 seconds before proceeding with unload
    var t = Date.now() + 300;
    while(Date.now() < t) {};
} 

Upvotes: 2

Related Questions