Browser tabs have revolutionized the way we browse the Web, but they’ve given us an tricky problem: developers can’t tell if the tab their site is displayed in is being viewed.
To solve that problem we have the Visibility API, which allows us to test whether the browser content can be seen, and respond accordingly.
It’s ideal for sites that play music for example, to pause the playback whilst the user is away.
The Page Visibility API comes with several properties:
- document.hidden: This property returns true if our page is hidden from the user. If it’s minimized or in a different tab.
- document.visibilityChange: This will trigger every time there is a change in the visibility of your page.
- document.visibilityState: This will tell you if your website is visible, hidden or in pre-render state.
These simple properties go a long way to allowing us to detect how a user is interacting with our site.
Browser support for this feature is good. All modern browsers support it, and you only really need the -webkit-prefix for Android and Blackberry browsers.
Let’s take a look at the code we need:
var hidden, state, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
state = "visibilityState";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
state = "webkitVisibilityState";
}
As you can see, we test whether document.hidden is undefined and then assign variables based on the result.
(This technique was first implemented by Sam Dutton back when there were a lot of prefixes to concern ourselves with.
Next, we need to listen for changes in the visibility state, which we do with a listener:
document.addEventListener(visibilityChange, function() {
// Code to manipulate the document
}, false);
Now we’re listening for a change and running a function each time it occurs. We can do anything we like inside that function; for the purposes of demonstration we’ll change the message on the page:
document.addEventListener(visibilityChange, function() {
if(document.visibilityState == hidden) {
document.title = ' Where are you going?';
} else {
document.title = 'Oh good you are back.';
}
}, false);
This code doesn’t affect the page when it first loads, only if the user changes the visibility of the page. If you want to set a different message as soon as the page loads you’d use something like:
document.title = 'Default Title';
Just by adding this the page will use this as default and then change the title according to the visibility state.