Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 its an internal application that doesn't play well with such a scenario so had to do it.

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 ?

share|improve this question
3  
hmm interesting problem and solution. Welcome to CR! – RubberDuck Nov 18 '14 at 12:16
    
Thank You.....! – Ali Kazmi Nov 18 '14 at 14:33

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('<div class="error">' + 
                '<h1>Sorry!</h1>' + 
                '<p>You can only have one instance of this web page open at a time.</p>' + 
                '</div>');
            });
    }
}(jQuery));

(code untested).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.