2016-07-14 67 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); 

希望這有助於。

相關問題