What is the page visibility API?

The web keeps growing and getting more sophisticated. Hence, more support is being poured into the web, giving it the ability to do things native to the operating system.

An example of such support is the Page Visibility API. The Page Visibility API fires off a visibilitychange event when a document becomes visible or hidden.

The visibilitychange event

When a user opens a new tab, a visibilitychange event is fired. This enables users to hook into the event and take action accordingly.

Also, the visibilitychange event is fired when we navigate to the previous tab.

This event includes more than moving to a new tab. The visibiltychange event is fired when:

  • the browser window is minimized
  • the browser window loses focus
  • the browser window is moved to the background in the OS

This API is helpful in many cases. For example, we wouldn’t want a video or audio to still be streaming when the tab is not active. We would want our video or audio to pause when we move to other tabs, and to continue when we move back to it.

Using the Page Visibility API

To use the Page Visibility API, we register a visibilitychange event in the document.

 document.addEventListener("visibilitychange", ()=> {
        ...
    })

Now, the function callback will be called when the tab is either active or inactive. We have to check from inside the function callback to know if the document is hidden or not by accessing the document.hidden property.

document.addEventListener("visibilitychange", ()=> {
        if(document["hidden"]) {
            ...
        } else {
            ...
        }
    })

Lastly, we will process our foreground task and background tasks between the if-else statement.

Free Resources