How to restrict your web app to a single instance

When building complex web applications it is often necessarry to restrict the user to keeping only a single instance open, and to do this you need to check for the precense of an existing instance, either directly or indirectly.

One way of doing this indirectly would be to set a cookie using javascript when the page loads and then use the unload event to remove the cookie. This means that as long as there is an instance open, the cookie will be set, and this can be tested for when the page loads.

window.onload = function(){
    if (document.cookie.indexOf("_instance=true") === -1) {
        document.cookie = "_instance=true";
        // Set the onunload function
        window.onunload = function(){
            document.cookie ="_instance=true;expires=Thu, 01-Jan-1970 00:00:01 GMT";
        };
        // Load the application
    }
    else {
        // Notify the user
    }
};

The disadvantage of doing it this way is that you increase the amount of data being sent to the server with each request as all cookies are being sent, but the cookie could be restricted to the documents path so that it would not be sent with non-matching requests.

The direct way would be to try to get a reference to the existing window using its name, but this does involve using window.open, which means the method could be blocked and rendered unreliable by popup blockers. But then again, complex application often need popups to be enabled and one could use this to check for and alert the user about the popup blocker.

window.onload = function(){
    var doLoad = false, name = "unique_name", existing = window.open("", name, "");
    if (!existing) {
        // Notify the user about allowing popups
        alert("Popup blocker detected\nPlease allow popups for this domain.");
        return;
    }
    if (window === existing) {
        doLoad = true;
    }
    else {
        if (existing.document.title !== window.document.title) {
            // The referenced window is not an existing instance
            doLoad = true;
            existing.close();
            window.name = name;
        }
    }
    if (doLoad) {
        // Load the application
    }
    else {
        // Notify user
    }
};

Which way you choose is entirely up to you.
If you know any other ways, feel free to add it in the comments 🙂

Tags: ,

This entry was posted on Sunday, November 15th, 2009 at 17:37 and is filed under programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.