I want to write javascript that will kill sestion on the web page if user did not make any action for some time taken from configuration. How can I know that user did not make any actions by using jQuery.
Thanks a lot.
You could trap the mousedown and keydown events for the entire document, and then setup a timeout to run if the events are not raised within a certain timeframe:
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var _idleEventId = null;
var _idleMaxMilliSeconds = 10000;
function OnIdle() {
alert('You\'re idle!');
}
$(document).bind("mousedown keydown", function() {
clearTimeout(_idleEventId);
_idleEventId = setTimeout(OnIdle, _idleMaxMilliSeconds);
});
$(document).ready(function() {
_idleEventId = setTimeout(OnIdle, _idleMaxMilliSeconds);
});
</script>
</head>
<body>
Hello World
</body>
</html>
how to use cookie just in case: http://www.w3schools.com/JS/js_cookies.asp
then i would have like this
NOTE: just a proof of concept not tested!
setInterval("checkForActivity()", 5000); //set a reasonable time..
function checkForActivity() {
var user_has_moved_at = (new Date()).getTime(); //generate a time
var time_elapsed = getCookie( COOKIE_NAME ); //get a time from previous stored
//check how many time is passed from last move
if ( ( user_has_moved_at - time_elapsed ) < 3600 ) {
//less then 1 hour.. user is still here..
$(document.body).bind('mousemove',
function() {
// so update the fresh air...
setCookie( COOKIE_NAME , user_has_moved_at);
// unbind event
$(document.body).unbind('mousemove');
});
} else {
// more then 1 hour... destroy cookie... user is out
setCookie(COOKIE_NAME, null); //destroy cookie
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With