Archive for the ‘automatic logout’ tag
Auto-logout after some time of inactivity with JavaScript
Logging out a user after a particular period of inactivity is a good measure(!?) to ensure that the user is there attending the screen and has not left it unattended. I have commonly seen such implementation while reading my webmails. If there is no activity for 5 minutes, I am auto-logged out because the system assumes that I may not be sitting in front of the PC and hence somebody else may get an opportunity to read my emails.
Logic:
You can achieve the same inactivity-induced auto-logout by using javascript. The logic is:
- Start an timer as soon as the page loads.
- On every activity, reset the timer. Since there is no in-built javascript function to reset the timer, to reset the timer, we have to first clear the previous timer and then immediately implement another timer.
- If the timer runs out due to inactivity, redirect the user to your logout page
The JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <script type="text/javascript"> function set_interval() { //the interval 'timer' is set as soon as the page loads timer=setInterval("auto_logout()",10000); // the figure '10000' above indicates how many milliseconds the timer be set to. //Eg: to set it to 5 mins, calculate 5min= 5x60=300 sec = 300,000 millisec. So set it to 3000000 } function reset_interval() { //resets the timer. The timer is reset on each of the below events: // 1. mousemove 2. mouseclick 3. key press 4. scroliing //first step: clear the existing timer clearInterval(timer); //second step: implement the timer again timer=setInterval("auto_logout()",10000); ..completed the reset of the timer } function auto_logout() { //this function will redirect the user to the logout script window.location="your_logout_script_location_here"; } </script> |
The HTML tags
The body tag should listen to these 3 events to record activity.
- Mouse move
- Mouse click
- Key press
- Scrolling
The markup would thus be
1 2 3 4 | .
<body onmousemove="reset_interval()" onclick="reset_interval()" onkeypress="reset_interval()" onscroll="reset_interval()">
.
. |