Is there a way to detect if a browser window is not currently active?

前端 未结 19 2102
无人共我
无人共我 2020-11-21 04:40

I have JavaScript that is doing activity periodically. When the user is not looking at the site (i.e., the window or tab does not have focus), it\'d be nice to not run.

19条回答
  •  忘了有多久
    2020-11-21 04:48

    If you want to act on whole browser blur: As I commented, if browser lose focus none of the suggested events fire. My idea is to count up in a loop and reset the counter if an event fire. If the counter reach a limit I do a location.href to an other page. This also fire if you work on dev-tools.

    var iput=document.getElementById("hiddenInput");
       ,count=1
       ;
    function check(){
             count++;
             if(count%2===0){
               iput.focus();
             }
             else{
               iput.blur();
             }
             iput.value=count;  
             if(count>3){
               location.href="http://Nirwana.com";
             }              
             setTimeout(function(){check()},1000);
    }   
    iput.onblur=function(){count=1}
    iput.onfocus=function(){count=1}
    check();
    

    This is a draft successful tested on FF.

提交回复
热议问题