How to check browser tab visibility using Page Visibility API

A browser tab can be in one of three states: visible, hidden, or inactive. A tab is considered hidden when it is not in the foreground but it is still open. A tab is considered inactive when it is not visible and it is not the foreground tab. The Page Visibility API for JavaScript allows you to determine the visibility state of a tab. This API can be used to determine if a tab is hidden or inactive so that you can take appropriate action, such as hiding or disabling a toolbar.

The Page Visibility API is a new API that is supported by Chrome, Firefox, and Opera. Safari does not currently support the API.

The Page Visibility API is implemented as a property of the window object. The visibility state of a tab can be determined by reading the visibility property of the window object. The visibility property is a Boolean value that is true if the tab is visible, false if the tab is hidden, and undefined if the tab is inactive.

The following code sample demonstrates how to use the Page Visibility API to determine the visibility state of a tab.

<!DOCTYPE html>
<html>
<head>
<title>Page Visibility API</title>
<script type="text/javascript">
function updateVisibility() {
    var visibility = window.visibility;
    if (visibility == true) {
    document.getElementById("visible").innerHTML = "Tab is visible";
    } else {
    document.getElementById("visible").innerHTML = "Tab is hidden";
    }
}
</script>
</head>

<body>
    <h1>Page Visibility API</h1>
    <p>The Page Visibility API allows you to determine the visibility state of a tab.</p>
    <div id="visible">
    The tab is visible.
    </div>
    <button onclick="updateVisibility();">Update visibility</button>
</body>

</html>

In the code sample, the updateVisibility() function is called when the button is clicked. This function reads the visibility property of the window object and displays the text "Tab is visible" or "Tab is hidden" depending on the value of the visibility property.

💡
Need a writer? Want to work with me? I have a subscription copywriting service available at Zipply.io. Subscribe to a set number of words and split it into as many copy assets as you need. Scale your startup, small business, or MVP. Upgrade, downgrade and pause at any time. Start your subscription here.