jquery - javascript's unload and beforeunload alternative - Stack Overflow

I need to monitor when the user moves away from a page (to a different site not the same site) or close

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?

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?

Share Improve this question edited Apr 10, 2014 at 3:35 tshepang 12.5k25 gold badges97 silver badges139 bronze badges asked Sep 17, 2012 at 13:58 Robert AudiRobert Audi 8,5079 gold badges46 silver badges68 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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

A possible solution is to pare 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?

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744308877a4567852.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信