Foreground Detection

The Page Visibility API is useful for the Web application to know whether it is currently displayed on the front or not, especially to stop resource-intensive UI animations or data refreshing when it is not needed. On the mobile devices, the primary reason for that is to reduce the battery usage.

API glimpse

Returns true if the page is currently hidden.
Returns current visibility state: visible, hidden, prerender or unloaded.
An event fired when the visibility state of the page has changed.

Live Demo

Switch the browser tab to see the changes.

Initial page visibility was unknown.

Based on demo from MDN.

  • var target = document.getElementById('target');
    var hidden, visibilityChange;
    if (typeof document.hidden !== "undefined") {
      hidden = "hidden";
      visibilityChange = "visibilitychange";
    } else if (typeof document.mozHidden !== "undefined") {
      hidden = "mozHidden";
      visibilityChange = "mozvisibilitychange";
    } else if (typeof document.msHidden !== "undefined") {
      hidden = "msHidden";
      visibilityChange = "msvisibilitychange";
    } else if (typeof document.webkitHidden !== "undefined") {
      hidden = "webkitHidden";
      visibilityChange = "webkitvisibilitychange";
    } else {
      target.innerText = 'Page Visibility API not supported.';
    function handleVisibilityChange() {
      var timeBadge = new Date().toTimeString().split(' ')[0];
      var newState = document.createElement('p');
      newState.innerHTML = '<span class="badge">' + timeBadge + '</span> Page visibility changed to <b>' + (document[hidden] ? 'hidden' : 'visible') + '</b>.';
    document.addEventListener(visibilityChange, handleVisibilityChange, false);
    if (hidden in document) {
      document.getElementById('status').innerHTML = document[hidden] ? 'hidden' : 'visible';
  • <p>Switch the browser tab to see the changes.</p>
    <p>Initial page visibility was <b id="status">unknown</b>.</p>
    <div id="target"></div>
    <p><small>Based on demo from <a href="">MDN</a>.</small></p>