我有JavaScript,它周期性地执行活动。当用户没有在看站点时(例如,窗口或选项卡没有焦点),最好不要运行。

是否有一种方法可以使用JavaScript来做到这一点?

我的参考点:如果你正在使用的窗口不活跃,Gmail聊天就会播放声音。


当前回答

这在chrome 67和firefox 67上都适用,

if(!document.hasFocus()) {
    // do stuff
}

其他回答

从最初编写这个答案开始,由于W3C,一个新的规范已经达到了推荐状态。页面可见性API(在MDN上)现在允许我们更准确地检测页面何时对用户隐藏。

document.addEventListener("visibilitychange", onchange);

当前浏览器支持:

铬13 + Internet Explorer 10+ Firefox 10 + Opera 12.10+[阅读笔记]

下面的代码在不兼容的浏览器中退回到不太可靠的模糊/聚焦方法:

(function() {
  var hidden = "hidden";

  // Standards:
  if (hidden in document)
    document.addEventListener("visibilitychange", onchange);
  else if ((hidden = "mozHidden") in document)
    document.addEventListener("mozvisibilitychange", onchange);
  else if ((hidden = "webkitHidden") in document)
    document.addEventListener("webkitvisibilitychange", onchange);
  else if ((hidden = "msHidden") in document)
    document.addEventListener("msvisibilitychange", onchange);
  // IE 9 and lower:
  else if ("onfocusin" in document)
    document.onfocusin = document.onfocusout = onchange;
  // All others:
  else
    window.onpageshow = window.onpagehide
    = window.onfocus = window.onblur = onchange;

  function onchange (evt) {
    var v = "visible", h = "hidden",
        evtMap = {
          focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
        };

    evt = evt || window.event;
    if (evt.type in evtMap)
      document.body.className = evtMap[evt.type];
    else
      document.body.className = this[hidden] ? "hidden" : "visible";
  }

  // set the initial state (but only if browser supports the Page Visibility API)
  if( document[hidden] !== undefined )
    onchange({type: document[hidden] ? "blur" : "focus"});
})();

ie9及以下版本需要onfocusin和onfocusout,而所有其他都使用onfocus和onblur,除了iOS,它使用onpageshow和onpagehide。

U可以使用:

(function () {

    var requiredResolution = 10; // ms
    var checkInterval = 1000; // ms
    var tolerance = 20; // percent


    var counter = 0;
    var expected = checkInterval / requiredResolution;
    //console.log('expected:', expected);

    window.setInterval(function () {
        counter++;
    }, requiredResolution);

    window.setInterval(function () {
        var deviation = 100 * Math.abs(1 - counter / expected);
        // console.log('is:', counter, '(off by', deviation , '%)');
        if (deviation > tolerance) {
            console.warn('Timer resolution not sufficient!');
        }
        counter = 0;
    }, checkInterval);

})();

我的代码

let browser_active = ((typeof document.hasFocus != 'undefined' ? document.hasFocus() : 1) ? 1 : 0);
if (!browser_active) {
 // active
} 

简单的/立即检查:

if(document.hidden) {
  // do something
}

可见性变化事件:

document.addEventListener("visibilitychange", function() {
  console.log(document.visibilityState); // "hidden" or "visible"
}, false);

基于承诺的事件:

// An `await`able function that resolves when page visibility changes:
function visibilityChange(state="") {
  return new Promise(resolve => {
    document.addEventListener("visibilitychange", function() {
      if(!state || document.visibilityState === state) { 
        resolve(document.visibilityState);
        document.removeEventListener("visibilitychange", arguments.callee);
      }
    });
  });
}

// Use it like this:
await visibilityChange();
console.log(document.visibilityState);

// Or wait for page to become...
await visibilityChange("visible");
await visibilityChange("hidden");

(注:后两个解是我加到这个答案里的,因为这个问题现在已经结束了,我不能加我自己的答案。以防有人认为我抄袭了那篇文章而没有注明出处。)

这对我很有效

document.addEventListener("visibilitychange", function() {
      document.title = document.hidden ? "I'm away" : "I'm here";
});

演示:https://iamsahilralkar.github.io/document-hidden-demo/