JavaScript 在浏览器最小化时每 5 秒重新加载页面



实际上,当数据库中发生某些更新时,我们会播放通知声音,因此当浏览器最小化时,我尝试每5秒重新加载一次页面,这在Firefox中工作正常,但在Chrome中这不起作用。

场景:

最小化浏览器并使计算机处于空闲状态。

我尝试了两种方法:

方法一:

   <meta http-equiv="refresh" content="5;URL=http://example.com/" />

方法2:

 <script>
   $(document).ready(function () {
   setTimeout(function(){
    window.location.reload(1);
    }, 5000);
    });
 </script>

任何帮助都会很棒。

窗口模糊焦点事件可以检测窗口的视图状态。

例:

 var timer = null;
 //when the window is minimized or when user is in different tab . 
    window.addEventListener('blur', function(){
       timer = setInterval(function(){
          window.location.reload(1);
       },5000)
    }, false);

//when user is back to window
    window.addEventListener('focus', function(){
        //stop the page reload once 
        if(timer != null){
        clearInterval(timer);
      }
    }, false);

希望这有帮助。

最新更新