【问题标题】:How to automatically reload a page after a given period of inactivity如何在给定的不活动时间后自动重新加载页面
【发布时间】:2011-06-06 08:29:06
【问题描述】:

如果网页在给定时间段内没有任何活动,我如何自动重新加载网页?

【问题讨论】:

标签: javascript ajax


【解决方案1】:
<script type="text/javascript">
  var timeout = setTimeout("location.reload(true);",600000);
  function resetTimeout() {
    clearTimeout(timeout);
    timeout = setTimeout("location.reload(true);",600000);
  }
</script>

上面将每 10 分钟刷新一次页面,除非调用了 resetTimeout()。例如:

<a href="javascript:;" onclick="resetTimeout();">clicky</a>

【讨论】:

  • 隐含的 eval 是纯粹的邪恶!
【解决方案2】:

这可以在没有 javascript 的情况下完成,使用这个元标记:

<meta http-equiv="refresh" content="5" >

其中 content ="5" 是页面将等待刷新的秒数。

但你说只有在没有活动的情况下,那是一种什么样的活动?

【讨论】:

  • 无活动意味着最终用户不在办公桌上或浏览其他网站。我所指的站点上没有鼠标/KB 活动。
  • 很好的答案,认为这必须通过setInterval 完成,很高兴知道它的存在!
  • 赞成,尽管这不是答案,因为它没有捕获活动,但是当简单地寻找 javascript 刷新时,这个问题在谷歌搜索结果的顶部。因此,如果您只是想让页面在设定的时间间隔内自动刷新,这就是要走的路。
  • 我们可以使用 post 变量自动刷新吗?
  • 这不是在回答问题。如果有活动,它无论如何都会重新加载
【解决方案3】:

如果您想在没有活动的情况下刷新页面,那么您需要弄清楚如何定义活动。假设我们每分钟刷新一次页面,除非有人按下键或移动鼠标。这使用 jQuery 进行事件绑定:

<script>
     var time = new Date().getTime();
     $(document.body).bind("mousemove keypress", function(e) {
         time = new Date().getTime();
     });

     function refresh() {
         if(new Date().getTime() - time >= 60000) 
             window.location.reload(true);
         else 
             setTimeout(refresh, 10000);
     }

     setTimeout(refresh, 10000);
</script>

【讨论】:

  • 如果使用 60000 计算,为什么要将间隔设置为 10000?至少 5 回合会是假的?
  • 间隔低于不活动时间的原因是您希望以比实际不活动时间高得多的频率检查不活动时间。例如,如果不活动时间为 1 分钟,间隔为 1 分钟,如果用户在 1 秒后移动鼠标然后停止,则刷新只会在 2 分钟后发生。间隔越小刷新时间越准确。
【解决方案4】:

我还构建了一个不需要 jquery 的完整 javascript 解决方案。也许可以把它变成一个插件。我用它来进行流畅的自动刷新,但它看起来可以帮助你。

JSFiddle AutoRefresh

// Refresh Rate is how often you want to refresh the page 
// bassed off the user inactivity. 
var refresh_rate = 200; //<-- In seconds, change to your needs
var last_user_action = 0;
var has_focus = false;
var lost_focus_count = 0;
// If the user loses focus on the browser to many times 
// we want to refresh anyway even if they are typing. 
// This is so we don't get the browser locked into 
// a state where the refresh never happens.    
var focus_margin = 10; 

// Reset the Timer on users last action
function reset() {
    last_user_action = 0;
    console.log("Reset");
}

function windowHasFocus() {
    has_focus = true;
}

function windowLostFocus() {
    has_focus = false;
    lost_focus_count++;
    console.log(lost_focus_count + " <~ Lost Focus");
}

// Count Down that executes ever second
setInterval(function () {
    last_user_action++;
    refreshCheck();
}, 1000);

// The code that checks if the window needs to reload
function refreshCheck() {
    var focus = window.onfocus;
    if ((last_user_action >= refresh_rate && !has_focus && document.readyState == "complete") || lost_focus_count > focus_margin) {
        window.location.reload(); // If this is called no reset is needed
        reset(); // We want to reset just to make sure the location reload is not called.
    }

}
window.addEventListener("focus", windowHasFocus, false);
window.addEventListener("blur", windowLostFocus, false);
window.addEventListener("click", reset, false);
window.addEventListener("mousemove", reset, false);
window.addEventListener("keypress", reset, false);
window.addEventListener("scroll", reset, false);
document.addEventListener("touchMove", reset, false);
document.addEventListener("touchEnd", reset, false);

【讨论】:

  • 这很棒。希望你在这里得到更多的支持。不使用 JQuery 可以获得主要的奖励积分。
  • * 太好了 / 非常感谢 * 这是否用于检测触摸事件?
  • 嗯,你知道我不确定。当我创建它时,我没有太多使用 iPhone 或 iPad 的经验。
  • 英雄!这是完美的感谢。我将我的 PHP 会话设置为一个小时后过期,并且设置为刷新一个多小时。我认为这应该完成我所追求的不活动后注销功能。
  • 如果我想暂停一个不重置的计时器,请问您能提供一个解决方案吗?
【解决方案5】:

这个任务很容易在 html 标题部分使用以下代码

<head> <meta http-equiv="refresh" content="30" /> </head>

它会在 30 秒后刷新您的页面。

【讨论】:

  • 在我的问题中,我们需要检查是否有活动
  • 是的,亲爱的,那么您必须使用 Ajax 技术。更改特定 html 标签的内容
  • 以正确的语法使用上述答案。
  • 您回答的这个方法没有回答问题,因为问题是关于如果页面上没有激活如何重新加载,即使页面上有活动,您的解决方案也会自动强制重新加载页。此处搜索的答案是,如果在一段时间内没有鼠标或键盘在页面上使用,如何使其重新加载。注意:我告诉你这个是因为我上次回答时也犯了同样的错误,所以我改变了答案以适应问题。
【解决方案6】:

是的,亲爱的,那么您必须使用 Ajax 技术。更改内容 特定的html标签:

 <html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <title>Ajax Page</title>
        <script>
        setInterval(function () { autoloadpage(); }, 30000); // it will call the function autoload() after each 30 seconds. 
        function autoloadpage() {
            $.ajax({
                url: "URL of the destination page",
                type: "POST",
                success: function(data) {
                    $("div#wrapper").html(data); // here the wrapper is main div
                }
            });
        }
        </script>
    </head>
    <body>
    <div id="wrapper">
    contents will be changed automatically. 
    </div>
 </body>
 </html>

【讨论】:

    【解决方案7】:
    var bd = document.getElementsByTagName('body')[0];
    var time = new Date().getTime();
    
    bd.onmousemove = goLoad;
    function goLoad() {
        if(new Date().getTime() - time >= 1200000) {
            time = new Date().getTime();
            window.location.reload(true);
        }else{
            time = new Date().getTime();
        }
    }
    

    每次移动鼠标时,它都会检查您上次移动鼠标的时间。如果时间间隔大于 20',它将重新加载页面,否则它将更新您上次移动鼠标的时间。

    【讨论】:

      【解决方案8】:

      我认为activity 是用户是否专注于窗口。例如,当您从一个窗口单击到另一个窗口时(例如,Google Chrome 到 iTunes,或 Internet 浏览器中的 Tab 1 到 Tab 2),网页可以发送回调说“我失焦了!”或“我在焦点!”。人们可以使用 jQuery 来利用这种可能缺乏活动的情况来做他们想做的任何事情。如果我处于你的位置,我会使用以下代码每 5 秒检查一次焦点,等等,如果没有焦点则重新加载。

      var window_focus;
      $(window).focus(function() {
          window_focus = true;
      }).blur(function() {
          window_focus = false;
      });
      function checkReload(){
          if(!window_focus){
              location.reload();  // if not focused, reload
          }
      }
      setInterval(checkReload, 5000);  // check if not focused, every 5 seconds
      

      【讨论】:

        【解决方案9】:

        基于 arturnt 接受的答案。这是一个略微优化的版本,但本质上是相同的:

        var time = new Date().getTime();
        $(document.body).bind("mousemove keypress", function () {
            time = new Date().getTime();
        });
        
        setInterval(function() {
            if (new Date().getTime() - time >= 60000) {
                window.location.reload(true);
            }
        }, 1000);
        

        唯一不同的是这个版本使用setInterval而不是setTimeout,这样代码更紧凑。

        【讨论】:

        • 如果使用60000计算,为什么要将间隔设置为1000
        • 间隔为 1.000,因为它每秒检查鼠标是否已移动。然后使用 60.000 来确定最后一次鼠标移动是否发生在至少一分钟前。
        【解决方案10】:

        使用您选择的目标自动重新加载。在这种情况下,目标是设置为自身的_self,但您可以通过简单地将window.open('self.location', '_self'); 代码更改为类似此示例window.top.location="window.open('http://www.YourPageAdress.com', '_self'"; 的内容来更改重新加载页面。

        带有确认 ALERT 消息:

        <script language="JavaScript">
        function set_interval() {
          //the interval 'timer' is set as soon as the page loads  
          var timeoutMins = 1000 * 1 * 15; // 15 seconds
          var timeout1Mins = 1000 * 1 * 13; // 13 seconds
          itimer=setInterval("auto_logout()",timeoutMins);
          atimer=setInterval("alert_idle()",timeout1Mins);
        
        }
        
        function reset_interval() {
          var timeoutMins = 1000 * 1 * 15; // 15 seconds 
          var timeout1Mins = 1000 * 1 * 13; // 13 seconds
          //resets the timer. The timer is reset on each of the below events:
          // 1. mousemove   2. mouseclick   3. key press 4. scrolling
          //first step: clear the existing timer
          clearInterval(itimer);
          clearInterval(atimer);
          //second step: implement the timer again
          itimer=setInterval("auto_logout()",timeoutMins);
          atimer=setInterval("alert_idle()",timeout1Mins);
        }
        
        function alert_idle() {
            var answer = confirm("Session About To Timeout\n\n       You will be automatically logged out.\n       Confirm to remain logged in.")
            if (answer){
        
                reset_interval();
            }
            else{
                auto_logout();
            }
        }
        
        function auto_logout() {
          //this function will redirect the user to the logout script
          window.open('self.location', '_self');
        }
        </script>
        

        无确认提醒:

        <script language="JavaScript">
        function set_interval() {
          //the interval 'timer' is set as soon as the page loads  
          var timeoutMins = 1000 * 1 * 15; // 15 seconds
          var timeout1Mins = 1000 * 1 * 13; // 13 seconds
          itimer=setInterval("auto_logout()",timeoutMins);
        
        }
        
        function reset_interval() {
          var timeoutMins = 1000 * 1 * 15; // 15 seconds 
          var timeout1Mins = 1000 * 1 * 13; // 13 seconds
          //resets the timer. The timer is reset on each of the below events:
          // 1. mousemove   2. mouseclick   3. key press 4. scrolling
          //first step: clear the existing timer
          clearInterval(itimer);
          clearInterval(atimer);
          //second step: implement the timer again
          itimer=setInterval("auto_logout()",timeoutMins);
        }
        
        
        function auto_logout() {
          //this function will redirect the user to the logout script
          window.open('self.location', '_self');
        }
        </script>
        

        两种解决方案的正文代码相同:

        <body onLoad="set_interval(); document.form1.exp_dat.focus();" onKeyPress="reset_interval();" onmousemove="reset_interval();" onclick="reset_interval();" onscroll="reset_interval();">
        

        【讨论】:

        • 这不是在回答问题。如果有活动,它将重新加载。
        • 你说得对,我没有阅读整个问题。好的,现在它已编辑正确答案。
        • 我去掉了 -1 并添加了 +10 以获得更好的答案!谢谢
        • 我也有第二个有效的答案,但现在我微调了这个答案,因为我现在编辑它可以更好地使用有针对性的解决方案。
        • 我现在为同一个解决方案给出了 3 个答案,具体取决于感觉更容易应用或满足需求。所有 3 种解决方案都有或没有确认或警报。我回答了 3 个答案,因为 3 个答案使用不同的代码,并且将所有解决方案放在一个答案中会太长。我还添加了关于如何编辑使用过的代码的说明。当然,所有答案都很完美......在我把它们放在这里之前已经过测试。
        【解决方案11】:

        使用页面确认文本而不是警报

        由于这是另一种在不活动时自动加载的方法,我给它第二个答案。这个更简单,更容易理解。

        页面上有重新加载确认

        <script language="javaScript" type="text/javascript">
        <!--
        var autoCloseTimer;
        var timeoutObject;
        var timePeriod = 5100; // 5,1 seconds
        var warnPeriod = 5000; // 5 seconds
        // Warning period should always be a bit shorter then time period
        
        function promptForClose() {
        autoCloseDiv.style.display = 'block';
        autoCloseTimer = setTimeout("definitelyClose()", warnPeriod);
        }
        
        
        function autoClose() {
        autoCloseDiv.style.display = 'block'; //shows message on page
        autoCloseTimer = setTimeout("definitelyClose()", timePeriod); //starts countdown to closure
        }
        
        function cancelClose() {
        clearTimeout(autoCloseTimer); //stops auto-close timer
        autoCloseDiv.style.display = 'none'; //hides message
        }
        
        function resetTimeout() {
        clearTimeout(timeoutObject); //stops timer
        timeoutObject = setTimeout("promptForClose()", timePeriod); //restarts timer from 0
        }
        
        
        function definitelyClose() {
        
        // If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
        // or  this: window.open('http://www.YourPageAdress.com', '_self');
        
        // of for the same page reload use: window.top.location=self.location;
        // or window.open(self.location;, '_self');
        
        window.top.location=self.location;
        }
        -->
        </script>
        

        与页面确认一起使用时的确认框

        <div class="leftcolNon">
        <div id='autoCloseDiv' style="display:none">
        <center>
        <b>Inactivity warning!</b><br />
        This page will Reloads automatically unless you hit 'Cancel.'</p>
        <input type='button' value='Load' onclick='definitelyClose();' />
        <input type='button' value='Cancel' onclick='cancelClose();' />
        </center>
        </div>
        </div>
        

        两者的正文代码相同

        <body onmousedown="resetTimeout();" onmouseup="resetTimeout();" onmousemove="resetTimeout();" onkeydown="resetTimeout();" onload="timeoutObject=setTimeout('promptForClose()',timePeriod);">
        

        注意:如果您不想在页面上进行确认,请使用无需确认

        <script language="javaScript" type="text/javascript">
        <!--
        var autoCloseTimer;
        var timeoutObject;
        var timePeriod = 5000; // 5 seconds
        
        function resetTimeout() {
        clearTimeout(timeoutObject); //stops timer
        timeoutObject = setTimeout("definitelyClose()", timePeriod); //restarts timer from 0
        }
        
        function definitelyClose() {
        
        // If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
        // or  this: window.open('http://www.YourPageAdress.com', '_self');
        
        // of for the same page reload use: window.top.location=self.location;
        // or window.open(self.location;, '_self');
        
        window.top.location=self.location;
        }
        -->
        </script>
        

        【讨论】:

        • 我现在为同一个解决方案给出了 3 个答案,具体取决于感觉更容易应用或满足需求。所有 3 种解决方案都有或没有确认或警报。我回答了 3 个答案,因为 3 个答案使用不同的代码,将所有解决方案放在一个答案中会太长。我还添加了关于如何编辑使用过的代码的说明。当然,所有答案都很完美......在我把它们放在这里之前已经过测试。
        【解决方案12】:

        最后是最简单的解决方案:

        带有警报确认:

        <script type="text/javascript">
            // Set timeout variables.
            var timoutWarning = 3000; // Display warning in 1Mins.
            var timoutNow = 4000; // Timeout in 2 mins.
        
            var warningTimer;
            var timeoutTimer;
        
            // Start timers.
            function StartTimers() {
                warningTimer = setTimeout("IdleWarning()", timoutWarning);
                timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
            }
        
            // Reset timers.
            function ResetTimers() {
                clearTimeout(warningTimer);
                clearTimeout(timeoutTimer);
                StartTimers();
                $("#timeout").dialog('close');
            }
        
            // Show idle timeout warning dialog.
            function IdleWarning() {
                var answer = confirm("Session About To Timeout\n\n       You will be automatically logged out.\n       Confirm to remain logged in.")
                    if (answer){
        
                        ResetTimers();
                    }
                    else{
                        IdleTimeout();
                    }
            }       
        
            // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
            function IdleTimeout() {
                window.open(self.location,'_top');
            }
        </script>
        

        没有警报确认:

        <script type="text/javascript">
            // Set timeout variables.
            var timoutWarning = 3000; // Display warning in 1Mins.
            var timoutNow = 4000; // Timeout in 2 mins.
        
            var warningTimer;
            var timeoutTimer;
        
            // Start timers.
            function StartTimers() {
                warningTimer = setTimeout(timoutWarning);
                timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
            }
        
            // Reset timers.
            function ResetTimers() {
                clearTimeout(warningTimer);
                clearTimeout(timeoutTimer);
                StartTimers();
                $("#timeout").dialog('close');
            }
        
            // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
            function IdleTimeout() {
                window.open(self.location,'_top');
            }
        </script>
        

        两种解决方案的正文代码相同

        <body onload="StartTimers();" onmousemove="ResetTimers();" onKeyPress="ResetTimers();">
        

        【讨论】:

        • 我现在为同一个解决方案给出了 3 个答案,具体取决于感觉更容易应用或满足需求。所有 3 种解决方案都有或没有确认或警报。我回答了 3 个答案,因为 3 个答案使用不同的代码,将所有解决方案放在一个答案中会太长。我还添加了关于如何编辑使用过的代码的说明。当然,所有答案都很完美......在我把它们放在这里之前已经过测试。
        【解决方案13】:

        使用 JavaScript setInterval 方法:

        setInterval(function(){ location.reload(); }, 3000);
        

        【讨论】:

          【解决方案14】:

          使用LocalStorage来跟踪上次activity的时间,我们可以写reload函数如下

          function reloadPage(expiryDurationMins) {
              const lastInteraction = window.localStorage.getItem('lastinteraction')
              if (!lastInteraction) return // no interaction recorded since page load
              const inactiveDurationMins = (Date.now() - Number(lastInteraction)) / 60000
              const pageExpired = inactiveDurationMins >= expiryDurationMins
              if (pageExpired) window.location.reload()
          }
          

          然后我们创建一个箭头函数,以毫秒为单位保存最后一次交互时间(字符串)

          const saveLastInteraction = () => window.localStorage.setItem('last', Date.now().toString())
          

          我们需要在浏览器中监听beforeunload 事件来清除我们的lastinteraction 记录,这样我们就不会陷入无限的重新加载循环。

          window.addEventListener('beforeunload', () => window.localStorage.removeItem('lastinteraction'))
          

          我们需要监控的用户活动事件是mousemovekeypress。我们存储用户移动鼠标或按下键盘上的键时的最后一次交互时间

          window.addEventListener('mousemove', saveLastInteraction)
          window.addEventListener('keypress', saveLastInteraction)
          

          为了设置我们的最终监听器,我们将使用load 事件。 在页面加载时,我们使用setInterval 函数来检查页面是否在一段时间后过期。

          const expiryDurationMins = 1
          
          window.addEventListener('load', setInterval.bind(null, reloadPage.bind(null, expiryDurationMins), 1000))
          

          【讨论】:

            【解决方案15】:

            我是这样做的:

            let lastActionTaken = new Date().getTime();
            function checkLastAction() {
              let now = new Date().getTime();
              if (now - lastActionTaken > 1000 * 60 * 60) window.location.reload();
              else lastActionTaken = now;
            }
            window.addEventListener("mousemove", checkLastAction);
            window.addEventListener("touchstart", checkLastAction);
            window.addEventListener("keydown", checkLastAction);
            

            一旦用户移动鼠标、按键或触摸触摸屏(如果该页面已闲置 1 小时),这将重新加载页面。此外,这也处理了focus,所以如果用户在不同的程序中移动他们的鼠标然后回到这个window,它将重新加载,这很好,因为关键是没有旧数据正在显示。

            【讨论】:

              【解决方案16】:

              许多其他答案要么没有回答“没有活动”的问题的主要部分,要么它们非常复杂,不必要。我已经接受了答案(这里:https://stackoverflow.com/a/4644315/9008140) 并修改它以利用您可以将计时器分配给变量的事实。这使我们可以摆脱第二个计时器以及时间戳。

              /**
              * create a timer that refreshes the page after the number of 
                minutes has passed without user interaction.
              * Moving the mouse or pressing a key on the current page will start 
                the timer over.
              * @param {any} minutes
              */
              var refreshTimer;
              function setPageRefreshTimer(minutes) {
                  var refreshInterval = minutes * 60 * 1000; //interval is in milliseconds.  We refresh every x minutes.
              $(document.body).bind("mousemove keypress", function (e) {
                  if (refreshTimer != null && refreshTimer != undefined) {
                      window.clearTimeout(refreshTimer);
                  }
                  refreshTimer = window.setTimeout(function () { window.location.reload(true); }, refreshInterval);
              });
              refreshTimer = window.setTimeout(function () { window.location.reload(true); }, refreshInterval);
              

              }

              此示例代码将根据传入的参数在几分钟内刷新,其准确性与 javascript 计时器一样高。在测试中,总是不到一秒。我将其创建为一个函数,但如果您愿意,您可以将其拉入您的页面。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2010-11-16
                • 1970-01-01
                • 2017-12-27
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多