Many times we have such a requirement to do some operations or prohibit some operations when the page is not displayed. The Page Visibility API provides convenience for us to achieve this requirement.
The API relies on the document object, there are two properties and one event, let’s take a look at it in turn.
Attributes
document.hidden
This attribute directly returns a boolean value indicating whether the page is hidden, because the attribute name is hidden, so returning true indicates that the current page is not visible. On the contrary, if it returns false, the page is visible.
console.log(document.hidden); // true or false
document.visibilityState
This attribute has almost the same function as document.hidden, except that the return value is different. What is returned is a string of visibility status, visible or hidden
console.log(document.visibilityState); // visible or hidden
Event
visibilitychange
By binding this event to the document, you can monitor changes in page visibility, whether you minimize the browser or jump to another page, it will be triggered.
Now combine the above attributes to write the simplest scenario implementation
document.addEventListener("visibilitychange", ()=>{
if(document.visibilityState === "hidden"){
console.log("hidden");
}else if(document.visibilityState === "visible"){
console.log("visible");
}
});
When the page visibility changes, determine the current visibility status and perform corresponding processing. The simplest piece of code can currently meet our needs.