2 min read

Idle Detection API

The Idle Detection API allows web applications to detect when a user is idle (not interacting with the keyboard, mouse, screen, etc.) or when the screen is locked. This is useful for chat applications (setting status to "Away"), stopping expensive computations, or automatically logging out users for security.

1. The Concept

Unlike setTimeout or mousemove listeners which only track activity within the browser window, the Idle Detection API detects system-wide idleness.

2. Permissions

Because this API can be used to track user behavior patterns, it requires explicit permission.

  • User Gesture: IdleDetector.requestPermission() must be called in response to a user action.
  • Secure Context: Only works on HTTPS (and localhost).
async function requestIdlePermission() {
  if (IdleDetector.requestPermission) {
    const state = await IdleDetector.requestPermission();
    if (state === 'granted') {
      console.log('Idle detection permission granted.');
      startIdleDetector();
    } else {
      console.log('Idle detection permission denied.');
    }
  }
}

3. Basic Usage

To use it, create an IdleDetector instance, set up an event listener, and call start().

async function startIdleDetector() {
  try {
    const controller = new AbortController();
    const signal = controller.signal;

    const idleDetector = new IdleDetector();

    idleDetector.addEventListener('change', () => {
      const userState = idleDetector.userState;
      const screenState = idleDetector.screenState;
      console.log(`Idle change: ${userState}, ${screenState}`);
    });

    // Start detection
    // threshold: time in ms before considering user idle (min 60000)
    await idleDetector.start({
      threshold: 60000,
      signal,
    });

    console.log('IdleDetector started');

  } catch (err) {
    console.error('Cannot start IdleDetector:', err);
  }
}

4. States

  • userState: 'active' or 'idle'.
  • screenState: 'locked' or 'unlocked'.

programming/javascript/vanilla/javascript programming/javascript/vanilla/events programming/javascript/vanilla/promises-async-await