Detect inactive users with the Idle Detection API

The Idle Detection API is part of the
capabilities project
and is currently in development. This post will be updated as the implementation progresses.

What is the Idle Detection API? #
The Idle Detection API notifies developers when a user is idle, …


This content originally appeared on web.dev and was authored by Thomas Steiner

The Idle Detection API is part of the capabilities project and is currently in development. This post will be updated as the implementation progresses.

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

Step Status
1. Create explainer Complete
2. Create initial draft of specification Complete
3. Gather feedback & iterate on design In progress
4. Origin trial In progress
5. Launch Not started

How to use the Idle Detection API

Enabling via chrome://flags

To experiment with the Idle Detection API locally, without an origin trial token, enable the #enable-experimental-web-platform-features flag in chrome://flags.

Enabling support during the origin trial phase

Starting in Chrome 88, the Idle Detection API is available as an origin trial in Chrome. The origin trial is expected to end in Chrome 90 (May 19, 2021).

Origin trials allow you to try new features and give feedback on their usability, practicality, and effectiveness to the web standards community. For more information, see the Origin Trials Guide for Web Developers. To sign up for this or another origin trial, visit the registration page.

Register for the origin trial

  1. Request a token for your origin.
  2. Add the token to your pages. There are two ways to do that:
    • Add an origin-trial <meta> tag to the head of each page. For example, this may look something like:
      <meta http-equiv="origin-trial" content="TOKEN_GOES_HERE">
    • If you can configure your server, you can also add the token using an Origin-Trial HTTP header. The resulting response header should look something like:
      Origin-Trial: TOKEN_GOES_HERE

An earlier origin trial for this feature ran from Chrome 84 to Chrome 86.

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 Chrome 86, you can emulate idle events in Chrome 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.

Share how you plan to use it on the WICG Discourse thread Send a Tweet to @ChromiumDev with the #idledetection hashtag and let us know where and how you're using it.

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.


This content originally appeared on web.dev and was authored by Thomas Steiner


Print Share Comment Cite Upload Translate Updates
APA

Thomas Steiner | Sciencx (2020-05-18T00:00:00+00:00) Detect inactive users with the Idle Detection API. Retrieved from https://www.scien.cx/2020/05/18/detect-inactive-users-with-the-idle-detection-api/

MLA
" » Detect inactive users with the Idle Detection API." Thomas Steiner | Sciencx - Monday May 18, 2020, https://www.scien.cx/2020/05/18/detect-inactive-users-with-the-idle-detection-api/
HARVARD
Thomas Steiner | Sciencx Monday May 18, 2020 » Detect inactive users with the Idle Detection API., viewed ,<https://www.scien.cx/2020/05/18/detect-inactive-users-with-the-idle-detection-api/>
VANCOUVER
Thomas Steiner | Sciencx - » Detect inactive users with the Idle Detection API. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2020/05/18/detect-inactive-users-with-the-idle-detection-api/
CHICAGO
" » Detect inactive users with the Idle Detection API." Thomas Steiner | Sciencx - Accessed . https://www.scien.cx/2020/05/18/detect-inactive-users-with-the-idle-detection-api/
IEEE
" » Detect inactive users with the Idle Detection API." Thomas Steiner | Sciencx [Online]. Available: https://www.scien.cx/2020/05/18/detect-inactive-users-with-the-idle-detection-api/. [Accessed: ]
rf:citation
» Detect inactive users with the Idle Detection API | Thomas Steiner | Sciencx | https://www.scien.cx/2020/05/18/detect-inactive-users-with-the-idle-detection-api/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.