The Page Visibility API

Do something with your webpage when your user switches tabs

Abinav Seelan
campvanilla
Published in
3 min readMar 17, 2018

--

The Page Visibility API provides us a means to know whether the user of our webpage is actively viewing the page or has moved the page to the background, by either switching tabs or minimizing the window.

MDN has a really good explanation for the API,

The Page Visibility API lets you know when a webpage is visible or in focus. With tabbed browsing, there is a reasonable chance that any given webpage is in the background and thus not visible to the user. When the user minimizes the webpage or moves to another tab, the API sends a visibilitychange event regarding the visibility of the page.

Building something simple with this API can help us better understand how it works.

How about changing the page title based on whether the user is active on the page or if the user has moved away? 🤔

Getting Started

Before we get started, we need a basic webpage.

☝️ is a simple webpage. It has a “😁” emoji as the page title and a single <script> tag where all our logic will reside.

Navigating away from the page

Whenever the user switches tabs or minimizes the window, the webpage receives an event called visibilitychange. This event can be handled by the document object, which has some data about the visibility state of the page .

Adding the event handler to document

Anytime the user switches tabs, the visibilitychange event is fired and here we’ve added a listener for this event to document. document.visibilityState holds the value of the current visibility state of the webpage — whether the page is hidden or visible.

Here, we check if its value is hidden and if so, we change the page title to “😴”.

Let’s see this in action!

The page title changes perfectly when we switch to another tab!

Returning to the page

Returning to the page also triggers the visibilitychange event, except here the document.visibilityState will be visible.

Let’s add that logic.

Now, running this gives us…

Looking good! 🎉

Where can I use this?

While the above example is extremely trivial, the Page Visibility API can come in handy if you need to:

  1. Perform a background data sync when the user is not on the page.
  2. Show the unread/unseen notification count in the title (similar to how twitter, gmail, etc do it)
  3. Show statuses (for example, Github updates it’s favicon to depict the status of a running build on the page)
  4. Pause content on the page. To take a few examples from MDN, you can pause video/audio on the page if the user switches tabs. Or prevent slideshows from advancing if the user is not currently on the page.

~Fin~

If you found this helpful, do leave a 👏!

Stuck somewhere, need more help, or just want to say hi? Hit me up on Twitter. You can also find me on Github. 🙃

--

--