The following code is a modification of what you'll find at the Mozilla Developer Network documentation for the Page Visibility API.
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
state = "visibilityState";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
state = "mozVisibilityState";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
state = "msVisibilityState";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
state = "webkitVisibilityState";
}
We need to determine the correct attribute names based on the browser. So utilizing the code above we will access our hidden property like this:
document[hidden]
as opposed to:
document.hidden
This will help keep our code compatible across browsers.
Whenever a user changes tabs and the visibility state changes, an event is fired. To listen to the event you can do the following:
document.addEventListener(visibilityChange, function() {
console.log(document[hidden]);
});
With the code above, you can switch tabs and it will log the state to the console.