Hide & seek with the Page Visibility API

Just like the Battery API, the Page Visibility API is a tiny but useful API (let's refer to them as "niche APIs"). It tells us wether a page is visible or not. Before this you always had to assume the page was visible, even when it was not.

Let's play a game!

Look up these questions in another tab, then check back to get a live demo of this API in action (actually, you don't have to look anything up, just switching tabs back and forth will do. :)

How does it work?

You can ask document.hidden to see if the document is hidden. Or you can ask for the document.visibilityState to see in what state the page is. This is useful as there are also the "pre-render" and the "unloaded" states besides the "visible" and "hidden" states.

Changes in these states trigger events, so you can do something when such a change occurs. You attach your event listeners to the document.onvisibilitychange event to listen in on visibility changes.


Sure. It's not as cool as CSS 3D-transforms, but it is pretty useful nonetheless. Especially uses in more complex web applications come to mind. Here's some other uses we (and others) have thought of for this API:

  • Auto-pause the game you're playing when it is hidden
  • Stop notifications from appearing when the page is visible (as you are already on the page, you probably won't need notifications)
  • Stop automatic polling of server data when the page is hidden, as the data won't be seen anyway (live statistics come to mind)
  • Automatically pause video when the page it is on becomes hidden (same goes for game sounds)
  • Prevent user views to be counted if the page has not yet become visible (still in pre-render state)

Whoopdidoo! Just one question: can I use it today?

Support for this API is actually pretty decent. Sure, you need to prefix for some of them, but that's how it is with pretty much all the fancy new stuff nowadays. The only browser that falls short on this is Safari, which is kind of disappointing.

Source, here!

Feel free to look around the differente source files we used for this example.