【问题标题】:Session timeout if the user is idle for certain time如果用户空闲一段时间,会话超时
【发布时间】:2014-04-02 08:10:48
【问题描述】:

您好,如果用户空闲 1 分钟,我将注销用户,并且我正在尝试延长会话超时 onkeypress、onmousemove、onmosueout 等。会话超时正在发生,但上述事件的会话超时延长没有发生。请在这方面帮助我。 我的代码:

var InactivityTime = function () {
    var t;
    window.onload = resetTimer();
    document.onmousemove = resetTimer();
    document.onkeypress = resetTimer();
    document.onmousedown = resetTimer();
    document.onmouseclick= resetTimer();
    document.onmouseup=resetTimer();

    function logout() {
        alert("Your session has been expired.Please Re-Login to continue");      
    }

    function resetTimer() {
        clearTimeout(t);
        t = setTimeout(logout, 60000);

        // 1000 milisec = 1 sec
    }
    return {
        //main function to initiate the module
        init: function () {           
            resetTimer();            
        }   
    };
}();

【问题讨论】:

    标签: javascript session timeout


    【解决方案1】:

    您需要在 init 函数中注册事件监听器,如下所示:

    return {
        //main function to initiate the module
        init: function () {           
            resetTimer();
            window.onload = resetTimer();
            document.onmousemove = resetTimer();
            document.onkeypress = resetTimer();
            document.onmousedown = resetTimer();
            document.onmouseclick= resetTimer();
            document.onmouseup=resetTimer();
        }
    };
    

    这些事件监听器似乎也是多余的。我会将它们简化为仅按键和鼠标移动。

    而调试的一个好方法是在resetTimer()函数中添加console.log()语句:

    function resetTimer() {
        clearTimeout(t);
        t = setTimeout(logout, 60000);
        console.log("reset");
        // 1000 milisec = 1 sec
    }
    

    【讨论】:

    • 您是否尝试过添加了 console.log() 消息?
    【解决方案2】:
    function InactivityTimer(path, delay) {
    
      // private instance var
      var timeout;
    
      // private functions
      function logout() {
        alert("you've been logged out");
        window.location.href = path || "/";
      }
    
      function reset() {
        stop();
        start();
      }
    
      function start() {
        if (!timeout) {
          timeout = setTimeout(logout, delay || 60000);
        }
      }
    
      function stop() {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
      }
    
      // export public api
      this.start = start;
      this.stop  = stop;
      this.reset = reset;
    
      // init
      document.addEventListener("mousemove", reset);
      document.addEventListener("keypress",  reset);
    }
    

    现在可以这样使用了

    var timer = new InactivityTimer("/logout", 60000);
    
    // maybe some other event stops the timer?
    timer.stop();
    
    // something else starts it back up
    timer.start();
    

    【讨论】:

      猜你喜欢
      • 2013-06-18
      • 1970-01-01
      • 2014-03-23
      • 2012-02-17
      • 2017-07-29
      • 2011-05-19
      • 2010-11-03
      • 2013-03-31
      • 2022-08-17
      相关资源
      最近更新 更多