Detect browser/tab closing

javascript, jquery

Solution

Not possible.

the only thing close is the `onbeforeunload` event, but there isn't a difference (to javascript) between a closed window/tab or a navigation to another page.

Follow-up:

I suppose you could attach a click handler to every anchor on the page and use a "dirty" flag, but that's really hack-ish. something like (forgive me, but using jquery for simplicity):

(function(){
  var closingWindow = true;
  $('a').on('click', function(){
    if (this.href == /* on-domain link */){
      closingWindow = false;
    }
  });
  $(window).on('beforeunload',function(){
    if (closingWindow){
      // your alert
    }
  });
})();

but that's about as close as you're going to get. note: this isn't going to help if another javascript function uses `window.location`, etc.

Problem

I know how to display an alert to the user if they attempt to navigate away from the current page asking them if they are sure they wish to do so but I was wondering if there is a way to display this alert ONLY when the window / tab is being closed? I'd like to only have the confirmation display when the window or tab is being closed, not when the user clicks a link.

Original source