How to check browser tab visibility using Page Visibility API

We can use the Page Visibility API to detect if a document is visible or not. Through this, we can stop unnecessary actions from being performed on the page.

Let’s say we have a page with a video or some background fetch to update the data or perform some animation. When we switch to another tab, we can improve performance or save memory by:

  • pausing the video
  • pausing the fetch in the background
  • pausing animation, which involves high computation

The Page Visibility API provides the following two properties under the document object:

  1. hidden: a boolean value for a document’s hidden state. If true, the document is hidden, as seen below:
document.hidden
  1. visibilityState: displays the current visibility state of the document. There are 4 states:
  • visible → the page is visible
  • hidden → the page is not visible
  • prerender → the page is loaded in the background, but is not visited by the user
  • unloaded → the page is in the process of being unloaded from memory.

prerender and unloaded are not supported in all browsers.

document.visibilityState

We also have the visibilitychange event to detect any change in the visibility of the page, as shown below:

document.addEventListener('visibilitychange', function(ev) {
   let state = document.visibilityState;
   if(state === "visible")
     console.log("Page is visible");
   else if(state === "hidden")
     console.log("Page is not visible");
});

In the code above, we can use the document.hidden property instead of the document.visibilityState.