繁体   English   中英

如何确定选项卡是否是给定浏览器窗口的活动(当前)选项卡?

[英]How to determine if a tab is the active (current) tab of a given browser window?

仅当标签是给定浏览器窗口中的活动/当前选项卡时,我才需要执行一些操作。

我试过这个:

let intID = setInterval(()=>{
  if(document.visibilityState == "visible"){
    //doSomething();
  }
}, 1000);

和这个:

let intID = setInterval(()=>{
  if(!document.hidden){
    //doSomething();
  }
}, 1000);

如果浏览器窗口被另一个最大化窗口覆盖,则上述两个示例都不起作用。 据我从网络上的其他文章中了解到,焦点模糊也不起作用。 我特别需要即使在完全覆盖甚至最小化的窗口中也能工作的东西。

我们可以使用Visibility API ,看这里的参考,包括我为你做的这个例子

https://jsfiddle.net/74xoqhza/

    // Set the name of the hidden property and the change event for visibility
  var hidden, visibilityChange;
  if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
    hidden = "hidden";
    visibilityChange = "visibilitychange";
  } else if (typeof document.msHidden !== "undefined") {
    hidden = "msHidden";
    visibilityChange = "msvisibilitychange";
  } else if (typeof document.webkitHidden !== "undefined") {
    hidden = "webkitHidden";
    visibilityChange = "webkitvisibilitychange";
  }
  
  
  // If the page is hidden, pause the video;
  // if the page is shown, play the video
  function handleVisibilityChange() {
    if (document[hidden]) {
      console.log('is hidden');
    } else {
      console.log('is focused');
    }
  }
  
  // Warn if the browser doesn't support addEventListener or the Page Visibility API
  if (typeof document.addEventListener === "undefined" || hidden === undefined) {
    console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
  } else {
    // Handle page visibility change
    document.addEventListener(visibilityChange, handleVisibilityChange, false);
  
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM