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

User Idle Detection

The User Idle API allows the Web application to detect the state when the user isn't active, i.e. there is no user-driven events generated in the system or the screen is locked. Contrary to the previous Foreground Detection capabilities, this API does not rely on the current tab activity – it detects when the user has been away from the device without locking it or has become inactive, regardless of which tab has been active.

As of Spring 2020, the API is at the early stage proposal, available in Google Chrome only using "Experimental Web Platform Features" flag.

This proposal does not address the system idle state, i.e. the state when the CPU isn't busy and previously delayed expensive operations might be initiated. To detect system idle state, the well-supported requestIdleCallback API exists.

API glimpse

const idleDetector = new IdleDetector(options)
Instantiates the IdleDetector object to be used to listen for events when the user goes idle.
idleDetector.start()
Starts observing for the user being idle.
const state = idleDetector.state
Exposes the current state: the state.user flag describing the user as either active or idle, and state.screen flag describing the display as locked or unlocked.
idleDetector.addEventListener('change', listener)
Register the listener to be called when the user's idle status has changed.

Live Demo

Stop your activity for 60 seconds and/or block the screen to record the idle state changes.

Based on the demo from the proposal.

  • var idleDetector;
    
    function handleIdleChange() { 
      const timeBadge = new Date().toTimeString().split(' ')[0];
      const newState = document.createElement('p');
      const {user, screen} = idleDetector.state;
      newState.innerHTML = '<span class="badge">' + timeBadge + '</span> User idle status changed to <b>' + user + '</b>. Screen idle status changed to <b>' + screen + '</b>.';
      target.appendChild(newState);
    }
        
    function startDetector() {
      if (!window.IdleDetector) {
        alert("Idle Detection API is not available");
        return;
      }
      
      const target = document.getElementById('target');
      
      try {
        idleDetector = new IdleDetector({ threshold: 60 });
        idleDetector.addEventListener('change', handleIdleChange);
        idleDetector.start();
      } catch (e) {
        alert('Idle Detection error:' + e);
      }
    }
  • <p><button onclick="startDetector()">Start idle detection</button></p>
    <p>Stop your activity for 60 seconds and/or block the screen to record the idle state changes.</p>
    <div id="target"></div>
    <p><small>Based on the demo from the <a href="https://github.com/samuelgoto/idle-detection" target="_blank" rel="noopener">proposal</a>.</small></p>

Resources

Get in touch