javascript reload page every 5 seconds when browser is minimized

血红的双手。 提交于 2019-12-02 08:12:09

问题


Actually we Play a notification sound when some update happens in database, so I am trying to reload page every 5 seconds when browser in minimized, this works fine in Firefox , but in Chrome this doesn't work.

Scenario:

Minimize the browser and leave the computer idle.

I have tried two methods:

Method 1:

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

Method 2:

 <script>

   $(document).ready(function () {

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

    });

 </script>

Any help would be great.


回答1:


The window blur and focus events can detect the view state of the window .

Example :

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

Hope this helps.



来源:https://stackoverflow.com/questions/38376157/javascript-reload-page-every-5-seconds-when-browser-is-minimized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!