从浏览器中检测浏览器内的选项卡切换和应用程序切换

时间:2018-05-21 08:50:20

标签: javascript jquery

当用户在特定浏览器中执行选项卡切换以及用户执行应用程序切换时,我需要了解选项卡的可见性状态。(从浏览器切换)

var visibilityState,
    activeTab = (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];
        }
    })();
activeTab(function() {
    visibilityState = activeTab();
});

用途

$(window).blur(function(){
    if(!visibilityState){
        console.log("Tab Switch happened ...");
    }
});

1 个答案:

答案 0 :(得分:0)

您的目标浏览器支持什么?你试过调查Page Visibility API吗?或者,如果你正在使用jQuery,你可以像answer那样$(window).on("blur focus", someCallbackHere)进行演示。