If you want to detect whether the tab is visible to the user, use document.visibilityState
to perform the check (a read-only property). Although document.hidden
works too, as others have written, then W3C considers it 'historical' and recommends using the former approach.
If you only want to know whether the tab is active, use document.hasFocus()
to perform the check. In this case, the tab could still otherwise be visible, but not active (e.g. two parallel view browser windows, where only one is active, both visible).
If you want capture the change to the state of visibility (and naturally also the active state in this case), then listen to the visibilitychange
event from the Page Visibility API.
Example using all three
// Capture change to visibility
document.addEventListener("visibilitychange", function() {
// Check if tab content is visible
if (document.visibilityState) {
console.log("Tab is visible!")
}
// Check if tab is active
if (document.hasFocus()) {
console.log("Tab is active!");
}
});
Handling browser compatibilities
You can set up the following checks to cover incompatible browsers.
Note: Does not include hasFocus()
as it's compatible all the way to IE6.
var visibilityState, visibilityChange;
if (typeof document.visibilityState !== "undefined") {
visibilityState = "visibilityState";
visibilityChange = "visibilitychange";
}
else if (typeof document.mozVisibilityState !== "undefined") {
visibilityState = "mozVisibilityState";
visibilityChange = "mozvisibilitychange";
}
else if (typeof document.msVisibilityState !== "undefined") {
visibilityState = "msVisibilityState";
visibilityChange = "msvisibilitychange";
}
else if (typeof document.webkitVisibilityState !== "undefined") {
visibilityState = "webkitVisibilityState";
visibilityChange = "webkitvisibilitychange";
}
if (visibilityChange != null && visibilityState != null) {
document.addEventListener(visibilityChange, function() {
if (document[visibilityState]) {
console.log("Tab is visible!")
}
}, false);
}
Quick MDN references