有没有一种方法来检测,如果浏览器窗口不是当前处于活动状态? [英] Is there a way to detect if a browser window is not currently active?

查看:417
本文介绍了有没有一种方法来检测,如果浏览器窗口不是当前处于活动状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JavaScript,定期做活动。当用户没有在现场看(即窗口或标签不具有焦点),它会是不错的无法运行。

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.

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

Is there a way to do this using JavaScript?

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

My reference point: Gmail Chat plays a sound if the window you're using isn't active.

推荐答案

由于最初写这个答案,一个新的规格已经达到的建议的状态得益于W3C。该页能见度API 使我们现在能够更准确地检测时,页面被隐藏到用户。

Since originally writing this answer, a new specification has reached recommendation status thanks to the W3C. The Page Visibility API now allows us to more accurately detect when a page is hidden to the user.

当前浏览器的支持:


  • 铬13 +

  • 的Internet Explorer 10 +

  • 火狐10 +

  • 歌剧12.10+ [阅读笔记]

以下code利用的API,回落到不兼容的浏览器不可靠模糊/对焦方式。

The following code makes use of the API, falling back to the less reliable blur/focus method in incompatible browsers.

(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 onfocusout在是的对于IE 9和更低必需的,而所有其他人利用的onfocus 的onblur ,除了iOS版,它使用 onpageshow onpagehide

onfocusin and onfocusout are required for IE 9 and lower, while all others make use of onfocus and onblur, except for iOS, which uses onpageshow and onpagehide.

这篇关于有没有一种方法来检测,如果浏览器窗口不是当前处于活动状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆