Use-Cases of this tutorial
- Know if the user is currently viewing the page or not.
- Know how to detect if user moves away from the current page to some other page or to do something else in the system.
- Know how to detect if user brings the page back into focus.
The Page Visibility API can be used to check whether a browser tab is active or not, i.e. if the page is in view or hidden from view.
Checking if Page in Visible to User or Hidden from View
The Page Visibility API adds 2 properties to the document object that can be used to check whether the user is currently viewing the page or not.
-
hidden : This property returns a boolean true or false depending on whether the page is visible to the user or not.
if(document.hidden) console.log('Page is hidden'); else console.log('Page is visible');
-
visibilityState : This property returns a string indicating the state of the page. The possible values can be :
- visible : The page or a part of the page is visible to the user.
- hidden : The page is not visible to the user.
var page_state = document.visibilityState; // "visible" / "hidden" console.log(page_state);
Detecting Change in Page Visibility
The visibilitychange event can be used to detect when the page goes to a hidden state from an active state or vice-versa.
document.addEventListener('visibilitychange', function() {
if(document.hidden)
console.log('Page is hidden from user view');
else
console.log('Page is in user view');
});