Click here to Skip to main content
15,892,005 members
Articles / Web Development / HTML
Tip/Trick

Single Instance Web Application

Rate me:
Please Sign up or sign in to vote.
4.79/5 (8 votes)
7 Mar 2015CPOL5 min read 21.5K   244   15   2
Run one instance of web application in client browser

Introduction

You may came across that user opened several instances of your web site at the same time and got confused. Another scenario, you may observe that when a web site auto refreshes itself, if there are more than one instances of it opened by a user, it consumes your server’s resources and makes the application slow.

You might be thinking you can have a technique to handle only a single instance of web application at client site. In this walkthrough, I will show you how to implement Single Instance of Web Application using JavaScript and Cookie. For this solution, browser should accept cookie.

This technique can be utilized in any kind of web technologies such as ASP, ASP .NET, JSP, HTML, CGI, etc. However, for this walkthrough, I am going to use ASP.NET.

1.0 Create ASP.NET Web Application

Using Visual Studio 2010, create a new ASP.NET Web Application. By default, Visual Studio creates several files for the application. In this demo, we are going to use Default.aspx as our landing page for the application. When user tries to start more than one instance of the application, we will redirect user to an error page. To manage Single Instance of the application, we are going to use onload and onunload events of the body tag from the Site.Master. JavaScript Function under the onload event will check for single instance using cookie and if necessary, it will redirect user to error page. JavaScript Function under the onunload event will clear the cookie.

Error page must have a separate master page or without any master page. Otherwise, it will fall in an infinite loop. Add a new “Web Form” and name it ErrorPage.aspx.

Under the Scripts folder, add a new “Jscript File” and name it SingleInstanceWebApp.js.

To test this application, we will need to run multiple instances of the application using browser. Hence, we need to run this application from IIS, instead of Visual Studio’s environment. Right click on the Project from Solution Explorer and select Properties option. Now, select Web tab. Click on the “Use Local IIS Web server”. This will update the “Project Url” based on your IIS setup. Next click on the “Create Virtual Directory”. If you prefer to create the web app from IIS directly, you may do that.

2.0 Add JavaScript to Project

Open Site.Master and add the following script references inside the Head section.

XML
<script src="Scripts/SingleInstanceWebApp.js" type="text/javascript"></script>

3.0 JavaScript Functions

Open SingleInstanceWebApp.js file from the Scripts folder. To manage cookie names for the application and error page, we need to setup few global variables.

JavaScript
// Name of the cookie for Single Instance App
var cookieSingleInstName = 'singleInstApp'; 
// Name of the cookie when user try to run more than one instance 
var cookieErrorMsg = 'singleInstAppMsg'// Cookie will expire in one day, if user continue to run the app without exit out browser 
var cookieExpireDays = 1; 
// This value will indicate, whether these cookies are set or not 
var cookieSetValue = '1';

Now, we need to define a function which will set the cookie. According to the parameter, it will either setup the cookie for the application or error page. For this demonstration, I use the cookies expiry day to 1. If user does not close the browser and after 24 hours, user opens the same application in different instance of browser, it will allow user to run. Depending on your requirements, you may set the cookieExpireDays value.

JavaScript
// SetCookie function sets the cookie with expire days

function SetCookie(name) {
  var d = new Date();
  d.setTime(d.getTime() + (cookieExpireDays * 24 * 60 * 60 * 1000));
  var expires = 'expires=' + d.toUTCString();
  document.cookie = name + '=' + cookieSetValue + '; ' + expires;
}

When user starts the application in browser, the onload event of body tag fired. From the site.master’s body tag, we will call the SetSingleInstance function. This function first checks whether cookie is setup or not. If there is no active cookie, it will set it up. Otherwise, it will setup error cookie and redirect user to ErrorPage.

JavaScript
// SetSingleInstance function verifies whether
// application is running or not. And setup corresponding
// cookies. This function will be called from onload events

function SetSingleInstance() {

  // Check this application is running. If true, then set the
  // Error message cookie and redirect user to ErrorPage
  if (GetCookie(cookieSingleInstName) == cookieSetValue) { // already opened
    SetCookie(cookieErrorMsg);
    document.location = "ErrorPage.aspx";
  }
  else { // first instance of the application
    // Set cookie for the application
    SetCookie(cookieSingleInstName);
  }
}

When user exits out of the application by closing the browser, the onunload event of the body tag fired. From the site.master’s body tag, we will call the RemoveSingleInstance function. Let me clarify a trick in this function. In happy path, user will open an instance of the application and close the browser before running again. For this scenario, the onunload event of body tag from site.master fired and called this function and we clear up the cookie. Think about this scenario, user opens an instance of the application in one browser. While this browser is open, user opens another browser and starts running the same application. In that case, the 2nd instance will call the SetSingleInstance function and redirect user to the error page. While it is going to error page, the onunload event will be fired. For this onunload event, we don’t want to remove the cookie for the application. To control this scenario, I am using cookieErrorMsg. This function first checks whether the cookieErrorMsg is set or not. If not, then it will clear up the application’s cookie. And the application is ready to run again without an error message.

JavaScript
// RemoveSingleInstance function removes the cookie for the application
// This function will be called from the onunload function
function RemoveSingleInstace() {
  // Check already running the application
  if (GetCookie(cookieErrorMsg) != cookieSetValue) {
    DeleteCookie(cookieSingleInstName);
  }
}

After redirecting user to ErrorPage, we need to clear the cookieErrorMsg. Hence, from the onload event of the body tag of ErrorPage, we need to call the RemoveErrorMsg. This function clears the cookie for error page.

JavaScript
// RemoveErrorMsg function clears the cookie
// which one was set before redirecting to ErrorPage
// This function will be called from the onload event of
// ErrorPage
function RemoveErrorMsg() {
  DeleteCookie(cookieErrorMsg);
}

According to the parameter’s value, the GetCookie function returns the value of the active cookie to the calling functions.

JavaScript
// GetCookie function returns the value of the cookie
function GetCookie(name) {
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var cvalues = ca[i].split('=');
    for (var j = 0; j < cvalues.length; j++) {
      if (cvalues[j].toString().trim() == name) {
        return cvalues[j + 1];
      }
     }
  }
  return '';
}

According to the parameter’s value, the DeleteCookie function makes the cookie expired.

JavaScript
// DeleteCookie function set the expire date to an earlier date
// to clear the cookie

function DeleteCookie(name) {
  document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
}

4.0 Call JavaScript Functions from Pages  

Open Site.Master page. In the body tag, add SingleInstance and RemoveSingleInstance functions.

HTML
<body onload="javascript:SetSingleInstance();" onunload="javascript:RemoveSingleInstace();">

Open ErrorPage.aspx file and add RemoveErrorMsg function in the body tag.

HTML
<body  onload = "javascript:RemoveErrorMsg();">

Onunload event must fire, while browser is closing the page. But you never know as we are not coding for browser. So, my suggestion is allow user to clear the cookie for the application manually. Hence, in the error page, I like to set a line for user and set a button to clear the cookie for the application. Add the following line in the body section of ErrorPage.aspx.

Another instance of SingleInstanceWebApp is running. 
If you think, it is a mistake, then click on 
<input id="ButtonClear" type="button" 
value="Clear" onclick="javascript:RemoveSingleInstace();"/>.

5.0 Testing the Application

Open a browser and type the URL, which depends on your IIS setup. For example, http://localhost/SingleInstanceWebApp/Default.aspx. Now open another instance of the same browser and type the same URL. You will see that the 2nd instance of the browser will redirect you to the ErrorPage.aspx.

6.0 Conclusion

This technique depends on the HTML’s body tag and JavaScript. Though I used ASP .NET and IIS for this walkthrough, you can implement it in other web technologies.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
United States United States
Team Lead and Application Developer in a wide variety of business application development. Particularly, interested in team managing and architecting application. Always, interested in solving complex problem.

Specialties: Team management, Agile, .Net Framework, Java, Database Design, MVVM, MVC, Enterprise Library, Prism

Comments and Discussions

 
GeneralMy vote of 4 Pin
Member 18804039-Mar-15 4:24
Member 18804039-Mar-15 4:24 
GeneralRe: My vote of 4 Pin
Pinakpani Dey9-Mar-15 6:51
professionalPinakpani Dey9-Mar-15 6:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.