Track the visibility of a page using Javascript

Introduction
Ever wondered how platforms such as Netflix play a short clip of a movie when we are in the tab and stop playing it when we switch the tab? There are two ways to achieve the functionality
1) Using onblur and onfocus
2) Using page visibility API
Onblur and Onfocus
Technically, the focus event gets triggered when an element receives focus and the blur event gets triggered when an element loses its focus.
When we attach focus and blur event listener to the window/document object, the blur event gets triggered in scenarios such as switching tabs and minimising the browser window. The focus event will be called when the page receives focus.
In this codepen based on the above event listeners, an audio clip is played.
Onblur and Onfocus are perfectly suited for our use case, which is auto-playing audio content based on tab visibility. However, if we look closely, the audio stops playing if there is any interaction outside of the document. For example, trying to bookmark a page.
This is happening because of onblur event. When the bookmark is clicked, the onblur event gets triggered because the document lost its focus.
However, the intention is to play the audio as long as the page is in view, irrespective of the actions we take like bookmarking or opening settings popup.
Page visibility API
The use case is to play the audio clip as long as the page stays in view irrespective of the actions.
Using onblur and onfocus is not accurate because syntactically they inform about enter/loss of focus. Hence, page visibility API serves as an appropriate alternative to track a page's visibility.
Page visibility essentially tells us if a page is visible or hidden. Page is hidden means either the user switched tabs, minimises the browser window or navigated to a different window.
In this codepen, page visibility API is used to ensure that the audio clip is played based on whether a page is visible or not. When we interact with actions outside of the document using this particular method it never stops playing the audio clip. This is because the page is still visible.
Conclusion
Whether to use onfocus/onblur combination or page visibility API is purely a use case-specific decision. However, if we have to track just the page visibility, onfocus/onblur gives us inaccurate results and functionality. Hence it is recommended to use page visibility API and the API is also widely supported across all browsers. There are numerous applications based on page visibility such as loading/unloading a resource and avoiding intensive calculations when the page is not visible.
Demo links
Subscribe to my newsletter
Read articles from lokprakash babu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

lokprakash babu
lokprakash babu
I am a frontend developer.