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

前端 未结 19 2113
无人共我
无人共我 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:54

    This is an adaptation of the answer from Andy E.

    This will do a task e.g. refresh the page every 30 seconds, but only if the page is visible and focused.

    If visibility can't be detected, then only focus will be used.

    If the user focuses the page, then it will update immediately

    The page won't update again until 30 seconds after any ajax call

    var windowFocused = true;
    var timeOut2 = null;
    
    $(function(){
      $.ajaxSetup ({
        cache: false
      });
      $("#content").ajaxComplete(function(event,request, settings){
           set_refresh_page(); // ajax call has just been made, so page doesn't need updating again for 30 seconds
       });
      // check visibility and focus of window, so as not to keep updating unnecessarily
      (function() {
          var hidden, change, vis = {
                  hidden: "visibilitychange",
                  mozHidden: "mozvisibilitychange",
                  webkitHidden: "webkitvisibilitychange",
                  msHidden: "msvisibilitychange",
                  oHidden: "ovisibilitychange" /* not currently supported */
              };
          for (hidden in vis) {
              if (vis.hasOwnProperty(hidden) && hidden in document) {
                  change = vis[hidden];
                  break;
              }
          }
          document.body.className="visible";
          if (change){     // this will check the tab visibility instead of window focus
              document.addEventListener(change, onchange,false);
          }
    
          if(navigator.appName == "Microsoft Internet Explorer")
             window.onfocus = document.onfocusin = document.onfocusout = onchangeFocus
          else
             window.onfocus = window.onblur = onchangeFocus;
    
          function onchangeFocus(evt){
            evt = evt || window.event;
            if (evt.type == "focus" || evt.type == "focusin"){
              windowFocused=true; 
            }
            else if (evt.type == "blur" || evt.type == "focusout"){
              windowFocused=false;
            }
            if (evt.type == "focus"){
              update_page();  // only update using window.onfocus, because document.onfocusin can trigger on every click
            }
    
          }
    
          function onchange () {
            document.body.className = this[hidden] ? "hidden" : "visible";
            update_page();
          }
    
          function update_page(){
            if(windowFocused&&(document.body.className=="visible")){
              set_refresh_page(1000);
            }
          }
    
    
      })();
      set_refresh_page();
    })
    
    function get_date_time_string(){
      var d = new Date();
      var dT = [];
      dT.push(d.getDate());
      dT.push(d.getMonth())
      dT.push(d.getFullYear());
      dT.push(d.getHours());
      dT.push(d.getMinutes());
      dT.push(d.getSeconds());
      dT.push(d.getMilliseconds());
      return dT.join('_');
    }
    
    function do_refresh_page(){
    
    // do tasks here
    
    // e.g. some ajax call to update part of the page.
    
    // (date time parameter will probably force the server not to cache)
    
    //      $.ajax({
    //        type: "POST",
    //        url: "someUrl.php",
    //        data: "t=" + get_date_time_string()+"&task=update",
    //        success: function(html){
    //          $('#content').html(html);
    //        }
    //      });
    
    }
    
    function set_refresh_page(interval){
      interval = typeof interval !== 'undefined' ? interval : 30000; // default time = 30 seconds
      if(timeOut2 != null) clearTimeout(timeOut2);
      timeOut2 = setTimeout(function(){
        if((document.body.className=="visible")&&windowFocused){
          do_refresh_page();
        }
        set_refresh_page();
      }, interval);
    }
    

提交回复
热议问题