Page Visibility API

Spread the love

The Page Visibility API tells you if the current page is visible or not and also informs you when the page becomes hidden or visible. 

This API is supported in almost all browsers, you can find the full list here.

Uses

Before we go into the details of the API, it is helpful to know why its useful to us.

When a page is in the background, you can do the following things

  • pause videos and animations so since the user is not looking at it anyway
  • Slow down or stop updates from your server thereby saving user bandwidth and lessening load on your servers.
  • Notify the user of events via notifications so that they can get back to your website.
  • Monitor how long users actually spend on your website and pages.

API Methods

document.hidden

document.hidden returns true if the entire page is currently hidden.

document.visibilityState

It has four possible values which specify finer level of detail about the visibility of the page.

a) Visible – Document is completely visible

b) hidden – Document is completely visible

c) Document is loaded but is offscreen

d) unloaded – the document is not loaded

visibilitychange

This is an event that you can listen to which gets triggered when the visibility of the page changes

Example:

document.addEventListener("visibilitychange", function(){
if(document.hidden == true){
console.log('the page is now completely hidden');
}else{
console.log('the page is now visible');
}
});