The web keeps growing and getting more sophisticated. Hence, more support is being poured into the web, giving it the ability to do things native to the operating system.
An example of such support is the Page Visibility API. The Page Visibility API fires off a visibilitychange
event when a document becomes visible or hidden.
visibilitychange
eventWhen a user opens a new tab, a visibilitychange
event is fired. This enables users to hook into the event and take action accordingly.
Also, the visibilitychange
event is fired when we navigate to the previous tab.
This event includes more than moving to a new tab. The visibiltychange
event is fired when:
This API is helpful in many cases. For example, we wouldn’t want a video or audio to still be streaming when the tab is not active. We would want our video or audio to pause when we move to other tabs, and to continue when we move back to it.
To use the Page Visibility API, we register a visibilitychange
event in the document.
document.addEventListener("visibilitychange", ()=> {
...
})
Now, the function callback will be called when the tab is either active or inactive. We have to check from inside the function callback to know if the document is hidden or not by accessing the document.hidden
property.
document.addEventListener("visibilitychange", ()=> {
if(document["hidden"]) {
...
} else {
...
}
})
Lastly, we will process our foreground task and background tasks between the if-else
statement.