2010-05-25 39 views
3

我想编写JavaScript,如果用户在配置过程中没有进行任何操作,将会终止网页上的sestion。 我如何知道用户没有使用jQuery进行任何操作。用jQuery控制用户操作

非常感谢。

+3

为什么你想在客户端做到这一点?您的服务器端语言应该已经配备了使会话无效的机制。 – Boldewyn 2010-05-25 12:18:15

+1

设置会话创建时的cookie超时? – baloo 2010-05-25 12:22:24

回答

3

您可以捕获整个文档,然后设置一个超时运行,如果该事件没有在一定时间内提高了鼠标按下和的keydown事件:

<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> 
+0

谢谢,但是与其他所有事件(如鼠标移动,鼠标点击或任何其他用户活动)有什么关系? – eomeroff 2010-05-25 12:41:07

+0

只需将它们添加为绑定参数:bind(“mousedown keydown mousemove etc”),在http://api.jquery.com/category/events/ – 2010-05-25 13:37:40

1

要检查,该用户没有做任何事情,你可以留意是否意味着用户交互事件:

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 
*/ 

clearTimeoutsetTimeout东西需要发生后护理的东西(即clear_da_session功能)有些时候没有发布任何列出的事件。

但是,我想重新强调一下我的评论:不要在家里做这个,孩子们!使用你的服务器端语言。这远比试图追踪某些东西更可靠,这可能是无法追踪的。

+0

啊,你打我吧:) – Jeriko 2010-05-25 12:26:35

+0

我认为更好地检查身体mousemove只是在一段时间不是每次! ;-) – 2010-05-25 13:01:26

+0

@aSeptik:你会怎么做?如果你检查,例如,在第二个5到6的时候移动鼠标,但用户在6到10秒内移动它,那么你在第二个10时发出错误的行为。是的,它*是一个表演噩梦,但嘿,我是谁来质疑OP的原因。 – Boldewyn 2010-05-25 13:20:46

2

如何使用饼干,以防万一: http://www.w3schools.com/JS/js_cookies.asp

那么我将不得不这样

注:只是一个概念证明没有测试!

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 
    } 

}; 
+0

找到整个列表我必须承认,这是一个很好的技巧。 +1 – Boldewyn 2010-05-25 14:07:20