Implementing Auto-Logout functionality

Here is small Javascript snippet which you will find useful for your web application. It will automatically redirect user to a specified page (for example Logout.aspx) after specific time of user inactivity, where you can delete session object etc.

<script type="text/javascript">
var timer;
var wait=10;
document.onkeypress=resetTimer;
document.onmousemove=resetTimer;
function resetTimer()
{
clearTimeout(timer);
timer=setTimeout("logout()", 60000*wait);
}

function logout()
{
window.location.href='Logout.aspx';
}
</script>

Snippet is self explanatory. setTimeout method which will call a function (logout function in above case) after specified delay in milliseconds. With that, it will reset the timer every time when there is a user movement on the page.

You need to drop this snippet in all pages (except login and unsecured pages) of your application. Master page is good place instead for easy and one place maintenance.

Before login off the user, you may probably prefer to alert user as well first. So let's extend above snippet further.

This gonna be bit tricky as we cannot use simple javascript alert to show that message. Instead we will create a DIV layer in the page and use it for showing alert message. Any user interaction will hide this alert message. After specific time of inactivity, user will navigate to Logout.aspx page where you can provide actual implementation to logout user and clear all session objects etc.

Here is modified code:

<html>
<head runat="server">
<title>Default Page</title>
<script type="text/javascript">
var timer1, timer2;
document.onkeypress=resetTimer;
document.onmousemove=resetTimer;
function resetTimer()
{
document.getElementById('timeoutPopup').style.display='none';
clearTimeout(timer1);
clearTimeout(timer2);

// waiting time in minutes
var wait=10;

// alert user one minute before
timer1=setTimeout("alertUser()", (60000*wait)-1);

// logout user
timer2=setTimeout("logout()", 60000*wait);
}

function alertUser()
{
document.getElementById('timeoutPopup').style.display='block';
}

function logout()
{
window.location.href='Logout.aspx';
}
</script>
<style type="text/css">
#timeoutPopup {
display:none; 
position:absolute; 
top:0; right:0; bottom:0; left:0;
width:30%;
height:30%;
margin:auto;
padding:4px;
border:solid 1px #999999; 
background-color:#dddddd;
text-align:center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="timeoutPopup">
Your session is about to expire if there is no additional 
activity.
</div>
</form>
</body>
</html>

Hope you will find this snippet useful.