Introduction
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 redirects to another site?
These are some of the frequently asked questions. Normally this is the requirement of any application. There is no fool-proof technique to catch the browser close event for 100% of the time. The trouble lies in the stateless nature of HTTP. I am explaining one of them which is very effective and tested.
I updated the article and now it support all kind of browser .
Using the Code
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 the following JavaScript code in your page or Master Page:
<script type="text/javascript">
var clicked = false;
function CheckBrowser()
{
if (clicked == false)
{
} else
{
clicked = false;
}
}
function bodyUnload()
{
if (clicked == false)
{
var request = GetRequest();
request.open ("POST", "../LogOut.aspx", false);
request.send();
}
}
function GetRequest()
{
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
</script>
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">
var clicked = false;
function CheckBrowser() {
if (clicked == false) {
}
else {
clicked = false;
}
}
function bodyUnload() {
if (clicked == false)
{
var request = GetRequest();
request.open("POST", "../LogOut.aspx", false);
request.send();
alert('This is close');
}
}
function GetRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
</script>
<body onunload="bodyUnload();" onclick="clicked=true;"><span style="font-size: 9pt;"> </span>
<form id="form1" runat="server">