Restricting user to one open tab in browser I had a requirement to restrict my web site's users to just one open tab in the browser. I am aware that this is not the best thing to do in terms of general user experience guidelines, but it's an internal application that doesn't play well with such a scenario so I had to do it.

The following is what I came up with:

function IsNewTab() {
  return $.cookie('TabOpen');
}

$(function() {
  if (!IsNewTab()) {
    $.cookie('TabOpen', "YES", {
      path: '/'
    });
    $(window).unload(function() {
      $.removeCookie('TabOpen', {
        path: '/'
      });
    });
  } else {
    alert('already some tab open')
      //OR
      //window.close()
  }
});


I'd like opinions on the above. Are there any loopholes (keeping in mind that the target audience isn't too technical and probably won't go hacking around with the browser console). Are there any possible improvements that can be made?
I can't think of a better approach than a session cookie. It feels safe in that you have three potential ways of leaving the page:


Navigate away
Close browser/tab
Browser crashes


So you're either going to have the option to remove the cookie on the unload event or the session cookie will expire anyway.

I would structure the code a little differently:

// Wrap in an IIFE accepting jQuery as a parameter.
(function ($) {
    var setCookie,
        removeCookie,
        // Create constants for things instead of having same string
        // in multiple places in code.
        COOKIE_NAME = 'TabOpen',
        SITE_WIDE_PATH = { path : '/' };

    setCookie = function () {
        $.cookie(COOKIE_NAME, '1', SITE_WIDE_PATH); 
    };

    removeCookie = function () {
        $.removeCookie(COOKIE_NAME, SITE_WIDE_PATH);
    };

    // We don't need to wait for DOM ready to check the cookie
    if ($.cookie(COOKIE_NAME) === undefined) {
        setCookie();
        $(window).unload(removeCookie);
    } else {
        // Replace the whole body with an error message when the DOM is ready.
        $(function () { 
            $('body').html('&lt;div class="error"&gt;' + 
                '&lt;h1&gt;Sorry!&lt;/h1&gt;' + 
                '&lt;p&gt;You can only have one instance of this web page open at a time.&lt;/p&gt;' + 
                '&lt;/div&gt;');
            });
    }
}(jQuery));


(code untested).