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.
<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.
var cookieSingleInstName = 'singleInstApp';
var cookieErrorMsg = 'singleInstAppMsg';
var cookieExpireDays = 1;
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.
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
.
function SetSingleInstance() {
if (GetCookie(cookieSingleInstName) == cookieSetValue) {
SetCookie(cookieErrorMsg);
document.location = "ErrorPage.aspx";
}
else {
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.
function RemoveSingleInstace() {
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.
function RemoveErrorMsg() {
DeleteCookie(cookieErrorMsg);
}
According to the parameter’s value, the GetCookie
function returns the value of the active cookie to the calling functions.
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.
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.
<body onload="javascript:SetSingleInstance();" onunload="javascript:RemoveSingleInstace();">
Open ErrorPage.aspx file and add RemoveErrorMsg
function in the body
tag.
<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.