DEV Community

Antonio Erdeljac
Antonio Erdeljac

Posted on

12

How to detect inactive users with Idle Detection API

This post is a summary of a web.dev article.

What is the Idle Detection API?

Idle Detection API is one of Chrome's origin trials, which means it is a feature in progress planned for a release.

Idle Detection API can be used to detect user inactivity based on a variety of measurements such as a mouse or keyboard inactivity, screensaver activation, or locking the screen. The threshold is defined by the developer, based on the desired result.

Usage of the Idle Detection API

Check if idleDetector is available:

const hasDetectorAPI = 'IdleDetector' in window;
Enter fullscreen mode Exit fullscreen mode

Request permission for idleDetector:

await IdleDetector.requestPermission();
Enter fullscreen mode Exit fullscreen mode

Starting the idleDetector:

const controller = new AbortController();
const signal = controller.signal;

const detector = new IdleDetector();

detector.addEventListener('change', () => {
  console.log(detector.userState); // idle | active
  console.log(detector.screenState); // locked | unlocked
});

await detector.start({
    threshold: 60000,
    signal,
});
Enter fullscreen mode Exit fullscreen mode

Use cases of Idle Detection API

Some examples where Idle Detection API can be utilized:

  • Apps with expensive computation (to put halt to computation)
  • Chatrooms (to handle activity status)
  • Forms / Documents (to autosave on user inactivity)

... and many other use cases.

Support Idle Detection API release

If you wish to see and use this API, check out this link on how to support its release.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
1e4_ profile image
Ian

Actually a pretty cool API. Hope it makes it to release. It basically takes away manually checking for mouse movement and focus events and puts it in a tidy API. Nice find

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay