Search code examples
jquerytabswindow.openpage-refresh

Detect Closed Tab in Base App


Is there a way in jQuery that I can detect a closed tab in my base app and make it refresh the page?

I built a ticketing system. When you click a ticket, it uses target="_blank" to open the ticket in a new tab. When you update a ticket (and only when you do so), and then click "Close Tab" link, I would like the main app (the previous tab) to recognize this event and automatically refresh the page.

I know that I can use window.open() and then detect a closed handle on a loop, but it's inelegant because on the IEs it doesn't open in a new tab sometimes and instead opens a new window. With target="_blank", I think I'm seeing that the IEs open a new tab. I prefer tabs.


Solution

  • So we have a parent tab with the ticket table, and then a child tab where we have an actual ticket. It's not truly a parent/child relationship, however, because I'm using target="_blank" clicks instead of window.open() events.

    The fix is kind of a kludge, but it works. The changes only need to be added to the "parent" tab. First, add a gbRefreshStale global boolean in Javascript to the page and set its value to 0 like so:

    var gbRefreshStale = 0;
    

    Second, on each target="_blank" click, intercept with jQuery like so:

    $('A[target=_blank]').click(function(){
      setTimeout('gbRefreshStale=1;clearTimeout();',500);
      return true;
    });
    

    Then, third, you'll need this mouseenter event for the header of the page:

    $('#header').mouseenter(function(){ 
      // assuming you called your banner/header as #header
      if (gbRefreshStale) {
        gbRefreshStale = 0;
        location.href = location.href;
      }
    });
    

    The effect here is that a new tab is opened for the ticket, but if someone closes that tab and passes their mouse across the header (which they will likely do since they just closed a child tab), the parent tab will refresh. This also works if multiple tabs are opened and closed, and this system prevents the parent tab from being refreshed in a loop. The timeout is necessary because otherwise someone's mouse might cross the #header section of the parent before that tab opens.