Determine if a tab has received focus from the user and how to handle events if the focus changes

The Page Visibility API gives us the power to determine when a page has focus. The API also triggers visibilitychange event when the focus of the page changes.
The Page Visibility API is super useful when we need to save resources in situations like:
- Not sending any network requests when the page is not being used by the user.
- Not executing the animations on a page that is not focused.
- Not updating any UI on a page that is not focused.
- Preventing the playback of media if a user is not on the page.
I think Medium also uses this API to determine the reading time of a story.
The Page Visibility API exposes two properties under document object:
document.hidden
Returns a boolean value representing whether the document is hidden or not.
document.visibilityState
A string representation of visibility state:
-
visibleâ The tab has focus. -
hiddenâ The tab is hidden. -
prerenderâ The page is loaded in the background but not visited by the user. -
unloadedâ The page is in the process of being unloaded from memory.
The prerender and unloaded states are not supported in all browsers.
In addition to the above properties, we also have an event visibilitychange. This event will be triggered when the browser tab gains or loses focus.
Example
document.addEventListener('visibilitychange', function(ev) {
console.log(`Tab state : ${document.visibilityState}`);
});
In the above example, we simply logged the state. But we can use the event to save resources or execute any desired code when the tab visibility changes.
document.addEventListener('visibilitychange', function(ev) {
// Stop animation
// Stop unwanted request
// Stop unwanted UI update
});
Using the Page Visibility API, matt-west created a video player which pauses the video when the page loses its focus and automatically plays again when the page gains focus.
Thanks for Reading đ . I hope you like this. If you found any typos or mistakes, send me a private note đ thanks đ đ .
Follow me JavaScript Jeepđđ¨Â .
Please make a donation here. 98% of your donation is donated to someone needs food đĽ. Thanks in advance.

















