检测浏览器选项卡是否处于活动状态或用户是否已切换

oli*_*rbj 47 javascript jquery

如何检测用户是否正在切换到另一个浏览器选项卡?

目前,我有这个:

$(window).on("blur focus", function (e) {

    var prevType = $(this).data("prevType");

    if (prevType != e.type) { //  reduce double fire issues
        switch (e.type) {
            case "blur":
                $('.message').html('<div class="alert alert-error">Oops. You navigated away from the ads <a id="start" class="butt green">Resume</a></div>');

                var myDiv = $("#bar");
                myDiv.clearQueue();
                myDiv.stop();
                clearInterval($timer);
                $timer = null;
                break;
            case "focus":
                // do work
                break;
        }
    }

    $(this).data("prevType", e.type);
});
Run Code Online (Sandbox Code Playgroud)

但这仅在用户最小化活动窗口时才有效.

Den*_*ret 144

现在我们可以使用可见性API.

为了处理不同的浏览器特定语法,我做了这个小代码:

var vis = (function(){
    var stateKey, eventKey, keys = {
        hidden: "visibilitychange",
        webkitHidden: "webkitvisibilitychange",
        mozHidden: "mozvisibilitychange",
        msHidden: "msvisibilitychange"
    };
    for (stateKey in keys) {
        if (stateKey in document) {
            eventKey = keys[stateKey];
            break;
        }
    }
    return function(c) {
        if (c) document.addEventListener(eventKey, c);
        return !document[stateKey];
    }
})();
Run Code Online (Sandbox Code Playgroud)

用法:

var visible = vis(); // gives current state

vis(aFunction);      // registers a handler for visibility changes
Run Code Online (Sandbox Code Playgroud)

示例:

vis(function(){
  document.title = vis() ? 'Visible' : 'Not visible';
});
Run Code Online (Sandbox Code Playgroud)

演示页面

  • @ Ali.NET我在所有浏览器上都使用它 (3认同)
  • @waterkinq 没有可靠的方法来对选项卡/浏览器关闭采取操作。这是一个设计选择(5年前情况有所不同)。这意味着您*永远*不能依赖浏览器通知断开连接,您必须在服务器端正确处理它。 (2认同)

Sah*_*kar 19

这 3 行代码对我有用

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

参考链接:document.hidden

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

  • 现在建议使用 [document.visibilityState](https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState) 而不是 [document.hidden](https://developer.mozilla .org/en-US/docs/Web/API/Document/hidden)。 (2认同)

rob*_*nix 9

如果要检测该选项卡是否对用户可见document.visibilityState,请使用来执行检查(只读属性)。尽管document.hidden正如其他人所写的那样,W3C 也认为它是“历史性的”,并建议使用前一种方法。

如果您只想知道该选项卡是否处于活动状态,请使用document.hasFocus()来执行检查。在这种情况下,选项卡仍然可以是可见的,但不是活动的(例如,两个并行视图浏览器窗口,其中只有一个是活动的,两个都可见)。

如果您想捕获可见性状态的更改(在本例中自然也包括活动状态),则可以侦听visibilitychange来自Page Visibility API 的事件。

使用所有三个的示例

// Capture change to visibility
document.addEventListener("visibilitychange", function() {
    // Check if tab content is visible
    if (document.visibilityState) { 
        console.log("Tab is visible!") 
    }

    // Check if tab is active
    if (document.hasFocus()) {
        console.log("Tab is active!");
    }
});
Run Code Online (Sandbox Code Playgroud)

处理浏览器兼容性

您可以设置以下检查来覆盖不兼容的浏览器。

注意:不包括,hasFocus()因为它一直兼容 IE6

var visibilityState, visibilityChange;
if (typeof document.visibilityState !== "undefined") {
    visibilityState = "visibilityState";
    visibilityChange = "visibilitychange";
} 
else if (typeof document.mozVisibilityState !== "undefined") {
    visibilityState = "mozVisibilityState";
    visibilityChange = "mozvisibilitychange";
} 
else if (typeof document.msVisibilityState !== "undefined") {
    visibilityState = "msVisibilityState";
    visibilityChange = "msvisibilitychange";
} 
else if (typeof document.webkitVisibilityState !== "undefined") {
    visibilityState = "webkitVisibilityState";
    visibilityChange = "webkitvisibilitychange";
}

if (visibilityChange != null && visibilityState != null) {
    document.addEventListener(visibilityChange, function() {
        if (document[visibilityState]) { 
            console.log("Tab is visible!") 
        }
    }, false);
}
Run Code Online (Sandbox Code Playgroud)

快速 MDN 参考


Roh*_*iya 7

情况1

只需将其添加到您的构造函数EventListener中即可。

document.addEventListener("visibilitychange", function() {
      if (document.hidden) {
        //do whatever you want
        console.log("Hidden");
      }
      else {
        //do whatever you want
        console.log("SHOWN");
      }
});
Run Code Online (Sandbox Code Playgroud)

案例2

请参阅此处如果您更改选项卡$(window).blur(function ()函数将调用,如果您再次来到此选项卡$(window).focus(function ()函数将调用。 在您的构造函数中添加此代码

$(window).focus(function () {
      //do something
       console.log("You are in this tab");
});

$(window).blur(function () {
      //do something
       console.log("You left this tab");
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Click here and click outside of this..</p>
Run Code Online (Sandbox Code Playgroud)