2016-07-14 90 views
1

其实我们在数据库中发生一些更新时播放通知声音,所以我试图在浏览器最小化时每5秒刷新一次页面,这在Firefox中正常工作,但在Chrome这不起作用。当浏览器被最小化时,JavaScript每5秒钟刷新一次页面

场景:

最小化浏览器,让计算机处于闲置状态。

我已经尝试了两种方法:

方法1:

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

方法2:

<script> 

    $(document).ready(function() { 

    setTimeout(function(){ 
    window.location.reload(1); 
    }, 5000); 

    }); 

</script> 

任何帮助将是巨大的。

+0

您无法从客户端javascript识别出浏览器窗口已最小化。 – VisioN

+0

@Vision,但即使在浏览器窗口最小化的情况下,自动重新加载也可以在Firefox中运行,为什么不在Chrome中? – stom

+0

为什么当您只能从服务器获取更新的数据时,您会重新加载整个页面?无论如何不会'window.location.href = window.location.href;'工作? – KRONWALLED

回答

1

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

例子:

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); 

希望这有助于。