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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19519535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:09:13  来源:igfitidea点击:

Detect if browser tab is active or user has switched away

javascriptjquery

提问by oliverbj

How can I detect if a user is switching to another browser tab?

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

Currently, I have this:

目前,我有这个:

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

But that only works when the user is minimizing the active window.

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

回答by Denys Séguret

Now we can use the visibility API.

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

To deal with the different browser-specific syntaxes, I made this small code :

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

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

Usage :

用法 :

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

vis(aFunction);      // registers a handler for visibility changes

Example :

例子 :

vis(function(){
  document.title = vis() ? 'Visible' : 'Not visible';
});

Demonstration page

演示页面