Can somebody tell me how can I close/kill the session when the user closes the browser? I am using stateserver mode for my asp.net web app. The onbeforeunload
method is not proper as it fires when user refreshes the page.
9 Answers
You can't. HTTP is a stateless protocol, so you can't tell when a user has closed their browser or they are simply sitting there with an open browser window doing nothing.
That's why sessions have a timeout - you can try and reduce the timeout in order to close inactive sessions faster, but this may cause legitimate users to have their session timeout early.

- 489,969
- 99
- 883
- 1,009
-
21facebook and gmail do it—anybody know how they achieve this? – NexusRex Jun 29 '11 at 21:09
-
12@NexusRex You can set a session cookie that expires when the browser is closed. That doesn't expire the session server side, but the browser won't have the token anymore. – Michael Stum Feb 20 '12 at 09:28
-
Ancient question/answer, but browsers restore session cookies. Chrome has done it since at least Chrome 19 (~2012). – ZachB Oct 17 '22 at 06:03
As said, the browser doesn't let the server know when it closes.
Still, there are some ways to achieve close to this behavior. You can put a small AJAX script in place that updates the server regularly that the browser is open. You should pair this with something that fires on actions made by the user, so you can time out an idle session as well as one that has closed out.

- 1,427
- 1
- 12
- 16
As you said the event window.onbeforeunload fires when the users clicks on a link or refreshes the page, so it would not a good even to end a session.
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx describes all situations where window.onbeforeonload is triggered. (IE)
However, you can place a JavaScript global variable on your pages to identify actions that should not trigger a logoff (by using an AJAX call from onbeforeonload, for example).
The script below relies on JQuery
/*
* autoLogoff.js
*
* Every valid navigation (form submit, click on links) should
* set this variable to true.
*
* If it is left to false the page will try to invalidate the
* session via an AJAX call
*/
var validNavigation = false;
/*
* Invokes the servlet /endSession to invalidate the session.
* No HTML output is returned
*/
function endSession() {
$.get("<whatever url will end your session>");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
This script may be included in all pages
<script type="text/javascript" src="js/autoLogoff.js"></script>
Let's go through this code:
var validNavigation = false;
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
A global variable is defined at page level. If this variable is not set to true then the event windows.onbeforeonload will terminate the session.
An event handler is attached to every link and form in the page to set this variable to true, thus preventing the session from being terminated if the user is just submitting a form or clicking on a link.
function endSession() {
$.get("<whatever url will end your session>");
}
The session is terminated if the user closed the browser/tab or navigated away. In this case the global variable was not set to true and the script will do an AJAX call to whichever URL you want to end the session
This solution is server-side technology agnostic. It was not exaustively tested but it seems to work fine in my tests

- 63,336
- 16
- 89
- 104

- 551
- 4
- 9
-
4Important to note that you have to make it a *synchronous* Ajax request, or it's extremely unlikely to get fired off at all. And of course, synchronous Ajax requests are ugly, they completely tie up the UI of the browser. – T.J. Crowder May 31 '10 at 17:19
-
@T.J. Crowder: ugly is an understatement when your server's having problems and a typical response time is more than 5 seconds :-) – Andy E May 31 '10 at 17:41
-
1Valid comments. How about a sync AJAX call with very small timeout?. Please consider that the proposed solution does not aim to resolve all the issues with orphans sessions. It would cover only a percent of them (user actively closes the browser and the logout URL responds ultra fast) – Daniel Melo May 31 '10 at 19:39
-
1This will still incorrectly terminate the session if the user refreshes their page or navigates back/forwards using the browser back/forwards buttons. – Simon Lieschke Jun 12 '12 at 01:56
-
I suggest you add: `//this code will handle the F5 or Ctrl+F5 key //need to handle more cases like ctrl+R whose codes are not listed here document.onkeydown = checkKeycode function checkKeycode(e) { var keycode; if (window.event) keycode = window.event.keyCode; else if (e) keycode = e.which; if(keycode == 116) { validNavigation = true; } }` like Saravanakumar [wrote](http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed/1922007#1922007) - it'll prevent terminating session on refresh – BornToCode Jan 21 '15 at 17:05
-
Using a `GET` request to destroy a session? I think `DELETE` or at least `POST` would be a better fit. – scaryguy Jun 12 '15 at 14:24
I do it like this:
$(window).bind('unload', function () {
if(event.clientY < 0) {
alert('Thank you for using this app.');
endSession(); // here you can do what you want ...
}
});
window.onbeforeunload = function () {
$(window).unbind('unload');
//If a string is returned, you automatically ask the
//user if he wants to logout or not...
//return ''; //'beforeunload event';
if (event.clientY < 0) {
alert('Thank you for using this service.');
endSession();
}
}

- 146,994
- 96
- 417
- 335

- 2,104
- 22
- 29
Please refer the below steps:
- First create a page SessionClear.aspx and write the code to clear session
Then add following JavaScript code in your page or Master Page:
<script language="javascript" type="text/javascript"> var isClose = false; //this code will handle the F5 or Ctrl+F5 key //need to handle more cases like ctrl+R whose codes are not listed here document.onkeydown = checkKeycode function checkKeycode(e) { var keycode; if (window.event) keycode = window.event.keyCode; else if (e) keycode = e.which; if(keycode == 116) { isClose = true; } } function somefunction() { isClose = true; } //<![CDATA[ function bodyUnload() { if(!isClose) { var request = GetRequest(); request.open("GET", "SessionClear.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>
Add the following code in the body tag of master page.
<body onbeforeunload="bodyUnload();" onmousedown="somefunction()">

- 22,600
- 28
- 79
- 90

- 31
- 2
Not perfect but best solution for now :
var spcKey = false;
var hover = true;
var contextMenu = false;
function spc(e) {
return ((e.altKey || e.ctrlKey || e.keyCode == 91 || e.keyCode==87) && e.keyCode!=82 && e.keyCode!=116);
}
$(document).hover(function () {
hover = true;
contextMenu = false;
spcKey = false;
}, function () {
hover = false;
}).keydown(function (e) {
if (spc(e) == false) {
hover = true;
spcKey = false;
}
else {
spcKey = true;
}
}).keyup(function (e) {
if (spc(e)) {
spcKey = false;
}
}).contextmenu(function (e) {
contextMenu = true;
}).click(function () {
hover = true;
contextMenu = false;
});
window.addEventListener('focus', function () {
spcKey = false;
});
window.addEventListener('blur', function () {
hover = false;
});
window.onbeforeunload = function (e) {
if ((hover == false || spcKey == true) && contextMenu==false) {
window.setTimeout(goToLoginPage, 100);
$.ajax({
url: "/Account/Logoff",
type: 'post',
data: $("#logoutForm").serialize(),
});
return "Oturumunuz kapatıldı.";
}
return;
};
function goToLoginPage() {
hover = true;
spcKey = false;
contextMenu = false;
location.href = "/Account/Login";
}

- 31
- 1
- 3
It is not possible to kill the session variable, when the machine unexpectly shutdown due to power failure. It is only possible when the user is idle for a long time or it is properly logout.

- 41
- 8
-
2Server-side, it doesn't make any difference at all if you're idle or your machine is turned off. client-side, you have no control whatsoever over session variables. – Alex Sep 11 '12 at 13:43
For browser close you can put below code into your web.config :
<system.web>
<sessionState mode="InProc"></sessionState>
</system.web>
It will destroy your session when browser is closed, but it will not work for tab close.

- 6,094
- 4
- 49
- 81
Use this:
window.onbeforeunload = function () {
if (!validNavigation) {
endSession();
}
}
Prevent F5, form submit, input click and Close/kill the session when the browser or tab is closed, tested in ie8+ and modern browsers, Enjoy!

- 513
- 2
- 7
- 24

- 695
- 7
- 16
-
1Consider that this solution only works in case your user allows executing javascript wherefore this could be a serious security issue. – flumingo Nov 13 '15 at 15:23
-
To those who want to use this solution as of today, this code does not handle browser refresh button press,back button press, forward button press, and hitting enter in URL bar of browser. the logout gets triggered when any of the mentioned events occur and also when tab/browser closed – NAK Jan 03 '18 at 11:56