Javascript unloads and redirects an alternative

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

+4
source share
2 answers

I think this is impossible, I do not know such an event.

A possible solution is to compare the current url with the destination URL, but this is not possible for security and privacy reasons:

How can I get destination url in javascript onbeforeunload?

+3
source

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 all links to external sites have the attribute rel="ext" .

+2
source

Source: https://habr.com/ru/post/1434622/


All Articles