Search posts

Javascript visibilty api

HTML 5 spec include nice api that allow us to know from the javascript if the page is visible to the user or not. we can also listen to event that is fired every time the visibility state change.

The java script event for change in visibility is visibilitychangeso we can listen to this event, and when it is fired to check if the page is visible.
For this we have two option. One is to check document.hiddenit will give us true if the page is hidden and false if the page is visible. The second option is to check document.visibilityStateand it will have the value visible and if the page is visible and the value hidden if the page is invisible.
In the example below we will only print to the console, but in your app you can use it to decide to stop video or presentation, mute sound, maybe even sending information to the server about the user interaction with the page.

//adding event listener to change in visibility state
document.addEventListener("visibilitychange", function () {
if (document.hidden){ //if document.hidden is true then the page is not visible, if document.hidden is false then page is visible
console.log("hidden");
} else {
console.log("visible");
}
if (document.visibilityState === "hidden"){
console.log("page is hidden")
}
if (document.visibilityState === "visible") {
console.log("page is visible");
}
})