What Web Can Do Today?

Can I rely on the Web Platform features to build my app?

An overview of the device integration HTML5 APIs

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.

This API does not detect the scenario when the page is still displayed on screen, but the user is idle (for example away). To detect this, the separate API proposal exists.

This API might be complemented with Freeze/Resume states detection to detect system-level generated lifecycle events for the application.

API glimpse

document.hidden
Returns true if the page is currently hidden.
document.visibilityState
Returns current visibility state: visible, hidden, prerender or unloaded.
document.addEventListener('visibilitychange')
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 the 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>.';
      target.appendChild(newState);
    }
    
    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 the demo from <a href="https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API" target="_blank" rel="noopener">MDN</a>.</small></p>

Resources

Get in touch