Monday, January 24, 2011

Clear Session On Browser Close

 

How to capture logoff time when user closes browser?

Or

How to end user session when browser closed?

Or

How to end user session when user redirect to another sites.

These are some of the frequently asked questions normally this is the requirement of any application.There is no full-proof technique to catch the browser close event for 100% of time. The trouble lies in the stateless nature of HTTP.I am explain one of them which is very effective and tested.

 

1. First create a page LogOut.aspx and in Page_Load event write this code:-

protected void Page_Load(object sender, EventArgs e)
{
Session.Abandon();
}




 


2. Then add following JavaScript code in your page or Master Page:-

<script type="text/javascript"> 
    var clicked = false;
function CheckBrowser()
{
if (clicked == false)
{
//Browser closed
}
else
{
//redirected
clicked = false;
}
}

function bodyUnload()
{
if (clicked == false)//browser is closed
{
var request = GetRequest();

request.open ("GET", "AutoLogOut.aspx", true);
request.send();
}
}

function GetRequest()
{
var request = null;
if (window.XMLHttpRequest)
{
//incase of IE7,FF, Opera and Safari browser
request = new XMLHttpRequest();
}
else
{
//for old browser like IE 6.x and IE 5.x
request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
return request;
}






3.  Add the following code in the body tag of master page.

<body onunload="bodyUnload();" Onclick="clicked=true;">








Finally the code in Master page like this:-


<script language="javascript" type="text/javascript">
//<![CDATA[

var clicked = false;
function CheckBrowser() {
if (clicked == false) {
//Browser closed
}
else {
//redirected
clicked = false;
}
}

function bodyUnload() {
if (clicked == false)//browser is closed
{
//var request = GetRequest();

//location.href = 'LogOut.aspx';
var request = GetRequest();

request.open("GET", "LogOut.aspx", true);
request.send();
}
}
function GetRequest() {
var request = null;
if (window.XMLHttpRequest) {
//incase of IE7,FF, Opera and Safari browser
request = new XMLHttpRequest();
}
else {
//for old browser like IE 6.x and IE 5.x
request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
return request;
}



//]]>
</script>

<body onunload="bodyUnload();" onclick="clicked=true;">
<form id="form1" runat="server">






3 comments:

  1. very nice.. but its not work in ff..

    ReplyDelete
  2. thank u very much. its really useful for me

    ReplyDelete

PDF Arabic watermark using MVC and iTextSharp

PDF full page Arabic watermark using MVC and iTextSharp Download :  Source Code Most of the time we have requirement to  gen...