Monitoring page shows hidden API

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.



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


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



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"){
    }else if(document.visibilityState === "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.

Leave a Reply