Best way to detect when a user leaves a web page?
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 the time required to terminate the browser).
Creating one will probably be blocked by current browsers.
Try the onbeforeunload
event: It is fired just before the page is unloaded. It also allows you to ask back if the user really wants to leave. See the demo onbeforeunload Demo.
Alternatively, you can send out an Ajax request when he leaves.
Mozilla Developer Network has a nice description and example of onbeforeunload.
If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data):
window.addEventListener('beforeunload', function(e) {
var myPageIsDirty = ...; //you implement this logic...
if(myPageIsDirty) {
//following two lines will cause the browser to ask the user if they
//want to leave. The text of this dialog is controlled by the browser.
e.preventDefault(); //per the standard
e.returnValue = ''; //required for Chrome
}
//else: user is allowed to leave without a warning dialog
});
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.