Anyone who has ever attempted to leverage the onbeforeunload or unload JavaScript events to detect when the browser window is closed becomes instantly disappointed to find that those events also fire when navigating to a new page.

I have a solution that is not fool-proof, but it’s a step in the right direction, and less complicated than solutions that rely on the “heartbeat“.

In my humble opinion, the vast majority of onbeforeunload events happen when a user clicks their mouse to navigate to a new page within your site. If we capture all mouse click events and record their timestamp, we can use that information to determine if a browser unload event was fired due to a link click.

Sample jQuery code:

if (!Date.now) {
    // a little polyfill for IE browsers that don't support Date.now
    Date.now = function() { return new Date().getTime(); }
}

var lastClickTime = 0;
$(window).click(function() {
    lastClickTime = Date.now();
});

$(window).bind('beforeunload', function() {
  var clickDiff = Date.now() - lastClickTime;
  if (clickDiff < 100)
    return;

  if (/* code that determines user is not logged out */) {
    alert('Wait, don\'t forget to log out!');
    return false;
  }
});

Leave a Reply

Your email address will not be published. Required fields are marked *