Best way to detect when a user leaves a web page?

前端 未结 8 2143
太阳男子
太阳男子 2020-11-22 01:57

What is the best way to detect if a user leaves a web page?

The onunload JavaScript event doesn\'t work every time (the HTTP request takes longer than t

8条回答
  •  爱一瞬间的悲伤
    2020-11-22 02:22

    Here's an alternative solution - since in most browsers the navigation controls (the nav bar, tabs, etc.) are located above the page content area, you can detect the mouse pointer leaving the page via the top and display a "before you leave" dialog. It's completely unobtrusive and it allows you to interact with the user before they actually perform the action to leave.

    $(document).bind("mouseleave", function(e) {
        if (e.pageY - $(window).scrollTop() <= 1) {    
            $('#BeforeYouLeaveDiv').show();
        }
    });
    

    The downside is that of course it's a guess that the user actually intends to leave, but in the vast majority of cases it's correct.

提交回复
热议问题