3

I am trying to track data in background when user leaves the website. This worked in firefox and chrome. But doesn't work on internet explorer. What is the correct way to use before unload event on Internet Explorer ?

$(window).bind('beforeunload', function () {
    $.post("track.php", {
        async: false,
        ip: ip,
        plansclick: plansclick,
    });
});
abc123
  • 17,855
  • 7
  • 52
  • 82
user198989
  • 4,574
  • 19
  • 66
  • 95
  • 1
    you verified that the beforeunload event isn't firing in IE? – abc123 Jul 04 '13 at 06:47
  • Yes, I verified. When you close the tab/browser, it doesn't send the data. – user198989 Jul 04 '13 at 06:54
  • i meant using a console.log event or an alert event. Just to verify the function is working. Then you'll need to add more complex code like the post in your example. – abc123 Jul 04 '13 at 06:57

1 Answers1

2

Appears to be an issue with the beforeunload event. This is described on jQuery.unload, as

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary beforeunload event.

beforeunload is more reliable than unload, but be sure to assign it directly (not bound through jQuery), like this:

window.onbeforeunload = function() { /* do stuff */ };

The unload event itself wasn't meant for work to be done, only cleanup of objects...as garbage collectors get better and better, there's less reason for the browser to even fire the unload event.

So you can try to convert your code to:

window.onbeforeunload = function () {
    $.post("track.php", {
        async: false,
        ip: ip,
        plansclick: plansclick,
    });
};

However, this functionality appears to not be guarenteed in any browser.

Possible Fix for jQuery.onbeforeunload
Duplicate issue on stackoverflow
Duplicate issue on stackoverflow 2
Duplicate issue on stackoverflow 3

Community
  • 1
  • 1
abc123
  • 17,855
  • 7
  • 52
  • 82