Abandoned computer on a bed with someone's leg next to it.

Detect inactive users with the Idle Detection API

Use the Idle Detection API to find out when the user isn't actively using their device.

Published on Updated on

What is the Idle Detection API?

The Idle Detection API notifies developers when a user is idle, indicating such things as lack of interaction with the keyboard, mouse, screen, activation of a screensaver, locking of the screen, or moving to a different screen. A developer-defined threshold triggers the notification.

Suggested use cases for the Idle Detection API

Examples of sites that may use this API include:

  • Chat applications or online social networking sites can use this API to let the user know if their contacts are currently reachable.
  • Publicly exposed kiosk apps, for example in museums, can use this API to return to the "home" view if no one interacts with the kiosk anymore.
  • Apps that require expensive calculations, for example to draw charts, can limit these calculations to moments when the user interacts with their device.

Current status

StepStatus
1. Create explainerComplete
2. Create initial draft of specificationComplete
3. Gather feedback & iterate on designIn progress
4. Origin trialCompleted
5. LaunchChromium 94

How to use the Idle Detection API

Feature detection

To check if the Idle Detection API is supported, use:

if ('IdleDetector' in window) {
// Idle Detector API supported
}

Idle Detection API concepts

The Idle Detection API assumes that there is some level of engagement between the user, the user agent (that is, the browser), and the operating system of the device in use. This is represented in two dimensions:

  • The user idle state: active or idle: the user has or has not interacted with the user agent for some period of time.
  • The screen idle state: locked or unlocked: the system has an active screen lock (like a screensaver) preventing interaction with the user agent.

Distinguishing active from idle requires heuristics that may differ across user, user agent, and operating system. It should also be a reasonably coarse threshold (see Security and Permissions).

The model intentionally does not formally distinguish between interaction with particular content (that is, the webpage in a tab using the API), the user agent as a whole, or the operating system; this definition is left to the user agent.

Using the Idle Detection API

The first step when using the Idle Detection API is to ensure the 'idle-detection' permission is granted. If the permission is not granted, you need to request it via IdleDetector.requestPermission(). Note that calling this method requires a user gesture.

// Make sure 'idle-detection' permission is granted.
const state = await IdleDetector.requestPermission();
if (state !== 'granted') {
// Need to request permission first.
return console.log('Idle detection permission not granted.');
}

Initially, idle detection was gated behind the notifications permission. While many, but not all, use cases of this API involve notifications, the Idle Detection spec editors have decided to gate it behind a dedicated idle detection permission.

The second step is then to instantiate the IdleDetector. The minimum threshold is 60,000 milliseconds (1 minute). You can finally start the idle detection by calling the IdleDetector's start() method. It takes an object with the desired idle threshold in milliseconds and an optional signal with an AbortSignal to abort idle detection as parameters.

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}.`);
});

await idleDetector.start({
threshold: 60000,
signal,
});
console.log('IdleDetector is active.');
} catch (err) {
// Deal with initialization errors like permission denied,
// running outside of top-level frame, etc.
console.error(err.name, err.message);
}

You can abort the idle detection by calling the AbortController's abort() method.

controller.abort();
console.log('IdleDetector is stopped.');

DevTools support

Starting in Chromium 94, you can emulate idle events in DevTools without actually being idle. In DevTools, open the Sensors tab and look for Emulate Idle Detector state. You can see the various options in the video below.

Idle Detector state emulation in DevTools.

Puppeteer support

As of Puppeteer version 5.3.1, you can emulate the various idle states to programmatically test how your web app's behavior changes.

Demo

You can see the Idle Detection API in action with the Ephemeral Canvas demo that erases its contents after 60 seconds of inactivity. You could imagine this being deployed in a department store for kids to doodle on.

Ephemeral Canvas demo

Polyfilling

Some aspects of the Idle Detection API are polyfillable and idle detection libraries like idle.ts exist, but these approaches are constrained to a web app's own content area: The library running in the context of the web app needs to expensively poll for input events or listen to visibility changes. More restrictively, though, libraries cannot tell today when a user goes idle outside of its content area (e.g., when a user is on a different tab or logged out of their computer altogether).

Security and permissions

The Chrome team has designed and implemented the Idle Detection API using the core principles defined in Controlling Access to Powerful Web Platform Features, including user control, transparency, and ergonomics. The ability to use this API is controlled by the 'idle-detection' permission. In order to use the API, an app also must be running in a top-level secure context.

User control and privacy

We always want to prevent malicious actors from misusing new APIs. Seemingly independent websites, but that in fact are controlled by the same entity, might obtain user idle information and correlate the data to identify unique users across origins. To mitigate these sort of attacks, the Idle Detection API limits the granularity of the reported idle events.

Feedback

The Chrome team wants to hear about your experiences with the Idle Detection API.

Tell us about the API design

Is there something about the API that doesn't work like you expected? Or are there missing methods or properties that you need to implement your idea? Have a question or comment on the security model? File a spec issue on the corresponding GitHub repo, or add your thoughts to an existing issue.

Report a problem with the implementation

Did you find a bug with Chrome's implementation? Or is the implementation different from the spec? File a bug at new.crbug.com. Be sure to include as much detail as you can, simple instructions for reproducing, and enter Blink>Input in the Components box. Glitch works great for sharing quick and easy repros.

Show support for the API

Are you planning to use the Idle Detection API? Your public support helps the Chrome team to prioritize features and shows other browser vendors how critical it is to support them.

Helpful links

Acknowledgements

The Idle Detection API was implemented by Sam Goto. DevTools support was added by Maksim Sadym. Thanks to Joe Medley, Kayce Basques, and Reilly Grant for their reviews of this article. The hero image is by Fernando Hernandez on Unsplash.

Updated on Improve article

We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.