Hi everyone,
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.
Hi everyone,
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.
To check, that a user didn't do anything, you could watch for events that signify user interaction:
var last_seen = 0;
var timeout = null;
$('body').mousemove(function () {
last_seen = (new Date()).getTime();
window.clearTimeout(timeout);
timeout = window.setTimeout(clear_da_session, 10000);
});
/* ... and likewise for things like
$('input').focus();
$('a').click();
and 'keypress' events
*/
The clearTimeout
and setTimeout
stuff takes care of something (i.e. the clear_da_session
function) happening after some time of not firing any of the listed events.
However, I want to re-emphasize my comment from above: Don't do this at home, kids! Use whatever your serverside language has on board. This is by far more reliable than trying to track something, that might be untrackable.
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
}
};