Detect tab focus and blur on all browsers and run callbacks
var hidden, visibilityState, visibilityChange;
        
            if (typeof document.hidden !== "undefined") {
                hidden = "hidden", visibilityChange = "visibilitychange", visibilityState = "visibilityState";
            }
            else if (typeof document.mozHidden !== "undefined") {
                hidden = "mozHidden", visibilityChange = "mozvisibilitychange", visibilityState = "mozVisibilityState";
            }
            else if (typeof document.msHidden !== "undefined") {
                hidden = "msHidden", visibilityChange = "msvisibilitychange", visibilityState = "msVisibilityState";
            }
            else if (typeof document.webkitHidden !== "undefined") {
                hidden = "webkitHidden", visibilityChange = "webkitvisibilitychange", visibilityState = "webkitVisibilityState";
            }
        
            document.addEventListener(visibilityChange, function(event){
                switch (document[visibilityState]) {
                    case "visible":
                        // tab is focused
                        break;
                    case "hidden":
                        // tab is blurred 
                        break;
                }
            });
by გიორგი უზნაძე
3 years ago
0
Pro tip: use ```triple backticks around text``` to write in code fences