小编典典

JavaScript有没有一种方法可以检测浏览器窗口当前是否未激活?

javascript

我的JavaScript会定期进行活动。当用户不查看站点时(即窗口或选项卡没有焦点),最好不要运行。

有没有办法使用JavaScript做到这一点?

我的参考点:如果您使用的窗口未激活,则Gmail聊天会播放声音。


阅读 648

收藏
2020-04-22

共1个答案

小编典典

自从最初编写此答案以来,新的规范已达到推荐状态。现在,页面可见性API使我们能够更准确地检测页面何时向用户隐藏。

document.addEventListener("visibilitychange", onchange);

当前的浏览器支持:

  • hrome 13+
  • Internet Explorer 10+
  • Firefox 10+
  • Opera 12.10+ [read notes]

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

(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"});
})();

onfocusin和IE 9及更低版本onfocusout是必需的focus,而其他所有语言都使用onfocusonblur(iOS除外,后者使用onpageshow和)onpagehide

2020-04-22