close-question

Solving the close browser / tab event issue

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;
  }
});

Why follow me on Twitter?

  • I tweet about new technologies, services or libraries I find interesting
  • Yeah, sometimes I'll post a pet-peeve or rant about something trivial
  • If I discover something that made my web development life easier, I share it
  • I'll shout out any handy tip that I think might be useful to other devs


This entry was posted in JavaScript. Bookmark the permalink.

Updated: 2015-04-29

Phil LaNasa follow us in feedly