4

I need to monitor when the user moves away from a page (to a different site not the same site) or closes the window/tab. I can achieve that with $(window).bind('unload', function() {}); but onload is a catch-all event: it also catches page refresh and navigating to a different page on the same website. How can I detect those two events (page refresh and navigating to another page in the same website) using javascript/jQuery please?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Robert Audi
  • 8,019
  • 9
  • 45
  • 67

2 Answers2

3

I think that isn't possible, I don't know such an event.

A possible solution is to compare the current url with the destination url but that's not possible because of security and privacy reasons see:

How can i get the destination url in javascript onbeforeunload event?

Community
  • 1
  • 1
Erwin
  • 4,757
  • 3
  • 31
  • 41
2

On each page,

var leaving = true;

$(function() {
    $('a[rel!=ext]').click(function () { leaving = false; });
    $('form').submit(function () { leaving = false; });
});

$(function() { window.onbeforeunload = unloadPage; });

function unloadPage() {
    if(leaving) {
        // Put your logic here
    }
}

Then just make sure that all links to external sites have a rel="ext" attribute.

mikeagg
  • 712
  • 3
  • 17
  • This won't work when the user types a new url in the navigation bar (probably to the same domain, or maybe not), this just works if the user clicks on links on the page. Also, you could have forms posting to a diferent domain. – Pablo Sep 20 '12 at 16:20
  • The unloadPage() handler does fire if the user types a new url (though I think not for Opera?). But if the new URL is within the for the current site then yes, you may get a false positive. – mikeagg Sep 20 '12 at 16:29
  • Forms posting to URLs outside the current site could be handled by coding more intelligent logic instead of simply setting leaving=false. – mikeagg Sep 20 '12 at 16:31