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
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.