Page Visibility API
January 24th, 2012To date, it has not been easy to tell, using JavaScript, whether the user can see your page or not. Sure, we have load, focus, blur and unload, but these have proven quirky and inconsistent in the past. Certain environments give us the ability to jump between windows and tabs, and even scroll pages without giving focus to the browser window. Automatic lock screens leave your web page active, but inaccessible. Further, Google is developing a feature for Chrome wherein a page can load and render before it is made visible to the end user.
If you’ve ever received a message on Facebook when it was the selected tab, but not necessarily the selected window and application, and it hasn’t made a noise, you’ve experienced some of this quirkiness.
So what can you do with this new API? You can slow down your application, suspend timers and clocks, and generally make your page behave better in a cooperative multitasking environment. In short, still more of what used to require Flash to implement no longer does.
Chrome introduced this new, simple API in 13 and the W3C has a group standardizing it. Firefox and IE will both see it added in their respective version 10 browsers.
To use it, you really only need to know two properties and one event.
The document.visibilityState property can be any one of four values, but the two most common (and only required) ones are hidden and visible. Now, when the page loads, you can know whether your content is actually exposed to the user or not.
The document.hidden provides a simple boolean.
Happily, the standards do partially specify how other applications can interact with these properties:
As examples, the attribute returns true when:
- The User Agent is minimized.
- The User Agent is not minimized, but the page is on a background tab.
- The Operating System lock screen is shown.
- The User Agent is minimized and a preview is shown.
The visibilityChange event will fire when this state changes after the initial page load, so you needn’t check it obsessively.
Note that Chrome uses the webkit prefix for this API, its properties and its event. Firefox and IE are expected to use the W3C version, without prefixes.


