How to know the browser tab is active or not

Javascript, Web Development, 2016-01-13 12:04:54 UTC

Today I am dealing with case when the tab is active, music is playing and if not music is pause. 

To solve this problem, I need an even listener.

Here is the code;

var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
    hidden = "hidden";
    visibilityChange = "visibilitychange";
} else if (typeof document.mozHidden !== "undefined") {
    hidden = "mozHidden";
    visibilityChange = "mozvisibilitychange";
} else if (typeof document.msHidden !== "undefined") {
    hidden = "msHidden";
    visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
    hidden = "webkitHidden";
    visibilityChange = "webkitvisibilitychange";
}

document.addEventListener(visibilityChange, handleVisibilityChange, false);

function handleVisibilityChange() {
    if(document[hidden]) {
        theMusic.play();
    }
    else {
        theMusic.pause();
    }
}

 

For complete explanation, you can visit Mozilla Developer site: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API

And stackoverflow topic; http://stackoverflow.com/questions/24705189/how-to-tell-if-browser-tab-is-active-and-turn-down-volume-sound-when-user-leave

 


Share: