# Idle Detection API

> How IdleDetector reports user and screen idle state, requests permission, handles policy errors, and falls back when unsupported.

`IdleDetector` reports whether the user has interacted with the device within a threshold you choose (at least one minute) and whether the screen is locked. It fires a `change` event when either state changes. The WICG draft gates access with the `idle-detection` permission and describes presence indicators in chat applications as a use case.

BCD `api.IdleDetector` records support from Chrome 94, Edge 94 through 95 and again from Edge 114, and mirrors Chrome support to the Chromium-derived browsers it lists. It records no support in Firefox or Safari. The [Idle Detection compatibility data](/compatibility/idle-detection/) gives the versions carried by this site's dataset.

## Syntax

```js
new IdleDetector()

IdleDetector.requestPermission()

idleDetector.start()
idleDetector.start(options)
```

The constructor takes no arguments. `requestPermission()` is a static method, `[Exposed=Window]` only, that returns a `Promise<PermissionState>` resolving to `"granted"`, `"denied"`, or `"prompt"`. `start()` returns a `Promise<undefined>` that resolves once the detector is `"started"`. The whole interface is `[SecureContext]` and is also exposed in dedicated workers, where `start()` works but `requestPermission()` does not exist.

## Parameters

`start()` takes one optional `options` argument, an `IdleOptions` dictionary.

| Member | Type | Required | Description |
|---|---|---|---|
| `threshold` | `unsigned long long` (`[EnforceRange]`) | No | Milliseconds of inactivity after which `userState` becomes `"idle"`. The minimum is 60,000; smaller values reject the promise. Negative or non-finite values throw a `TypeError` at the binding layer because of `[EnforceRange]`. |
| `signal` | `AbortSignal` | No | Aborting the signal stops the detector and rejects the pending `start()` promise with the signal's abort reason. |

Two read-only attributes carry the state: `userState` is `"active"` or `"idle"`, and `screenState` is `"locked"` or `"unlocked"`. Their initial value is `null`. Read state changes inside the `change` handler instead of treating the values immediately after `new IdleDetector()` as a reading.

## Exceptions

The specification defines the following rejections.

| Method | Exception | Condition |
|---|---|---|
| `requestPermission()` | `InvalidStateError` | The document is not fully active. |
| `requestPermission()` | `NotAllowedError` | The call has no transient user activation; the prompt can only follow a click or key press. |
| `start()` | `InvalidStateError` | The document is not fully active, or the detector's internal state is not `"stopped"` (it is already starting or started). |
| `start()` | `NotAllowedError` | The document is not allowed to use the `idle-detection` policy-controlled feature (default allowlist `'self'`), or the `idle-detection` permission state is `"denied"` when the detector is started. |
| `start()` | `TypeError` | `threshold` is below 60,000 ms. |
| `start()` | the signal's abort reason | `options.signal` is already aborted when `start()` is called, or is aborted while the promise is pending. |

Chromium departs from the specification in one place: when Permissions Policy blocks the feature, `start()` rejects with a `SecurityError`; the specification defines a `NotAllowedError` for this case (see the callout below). Chromium also rejects `start()` with `NotSupportedError` and the message `Idle detection not available.` when the browser-side monitor disconnects while the `start()` promise is still pending, a case the specification does not model.

Use the failure stage and exception name to choose a recovery. Move `requestPermission()` into a click or key handler after `NotAllowedError` from a call without transient activation. Keep the non-API branch active when permission is not granted. Raise `threshold` to at least `60_000` after `TypeError`. If a cross-origin frame gets a policy error, the embedding page can delegate the feature with `allow="idle-detection"`; the WICG specification gives the feature a default allowlist of `'self'`.

:::caution
Chromium's [`idle_manager.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/idle/idle_manager.cc) (chromium.googlesource.com), [`idle_detector.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/idle/idle_detector.cc) (chromium.googlesource.com) and [`permissions_strings.grdp`](https://chromium.googlesource.com/chromium/src/+/main/components/permissions_strings.grdp) (chromium.googlesource.com) define the following. `IdleDetector.requestPermission()` called without transient user activation rejects with `NotAllowedError: Must be handling a user gesture to show a permission request.` On Android and iOS builds the permission prompt text is `<origin> wants to know when you're actively using this device` (English locale); elsewhere the prompt lists the fragment `Know when you're actively using this device` after "This site would like to:". `start({ threshold: 30_000 })` rejects with `TypeError: Minimum threshold is 1 minute.`, and a `start()` on an instance whose detector is still started rejects with `InvalidStateError: Idle detector is already started.` A denied permission rejects with `NotAllowedError: Idle detection permission denied`.
:::

## Examples

Check for the constructor first. If it is absent or permission is not granted, use `visibilitychange` as a fallback signal for page visibility.

### Showing an "away" presence badge after one minute of inactivity

The permission request runs inside the `click` handler, which supplies the transient activation that `requestPermission()` requires. When the API is missing, the fallback marks the user away whenever the tab is hidden. Page visibility does not report system-wide presence.

```js
const badge = document.querySelector('#presence');
const enable = document.querySelector('#enable-presence');
let visibilityFallbackActive = false;

function markAway(isAway) {
  badge.textContent = isAway ? 'Away' : 'Active';
}

function startVisibilityFallback() {
  const syncVisibility = () => {
    markAway(document.visibilityState === 'hidden');
  };
  if (!visibilityFallbackActive) {
    document.addEventListener('visibilitychange', syncVisibility);
    visibilityFallbackActive = true;
  }
  syncVisibility();
  return 'fallback';
}

async function startPresence() {
  if (!('IdleDetector' in window)) {
    return startVisibilityFallback();
  }

  const state = await IdleDetector.requestPermission();
  if (state !== 'granted') return startVisibilityFallback();

  const detector = new IdleDetector();
  const syncBadge = () => {
    markAway(detector.userState === 'idle' || detector.screenState === 'locked');
  };
  detector.addEventListener('change', syncBadge);
  await detector.start({ threshold: 60_000 });
  syncBadge();
  return 'started';
}

enable.addEventListener('click', async () => {
  try {
    enable.hidden = (await startPresence()) !== 'denied';
  } catch (err) {
    console.error(`${err.name}: ${err.message}`);
  }
});
```

The fallback keeps the badge working with the narrower signal that the document became hidden or visible, including when permission is not granted. If the instance is named `idleDetector`, wait for startup with `await idleDetector.start()`; state changes still belong in the event handler.

### Stopping the detector with an AbortSignal when the user signs out

There is no `stop()` method. Pass an `AbortSignal` to `start()` when the application needs to end monitoring. Aborting after `start()` resolved cannot change that settled promise; aborting while `start()` is pending rejects it with the abort reason, so `catch` distinguishes a deliberate abort from another failure.

```js
const startWatch = document.querySelector('#start-idle-watch');
const signOut = document.querySelector('#sign-out');

async function watchUntilSignOut() {
  if (!('IdleDetector' in window)) return 'unsupported';

  const permission = await IdleDetector.requestPermission();
  if (permission !== 'granted') return permission;

  const detector = new IdleDetector();
  const controller = new AbortController();
  signOut.addEventListener('click', () => controller.abort(), { once: true });

  try {
    await detector.start({ threshold: 120_000, signal: controller.signal });
  } catch (err) {
    if (controller.signal.aborted) return 'stopped';
    throw err;
  }

  return 'started';
}

startWatch.addEventListener('click', async () => {
  try {
    startWatch.dataset.state = await watchUntilSignOut();
  } catch (err) {
    console.error(`${err.name}: ${err.message}`);
  }
});
```

After `controller.abort()` the detector returns to the `"stopped"` state and the same instance may be started again with a fresh signal; the old `userState` and `screenState` values are no longer updated.

## See also

- [Screen Wake Lock API](/reference/capabilities/wake-lock/), the complementary request to keep the screen from locking
- [Web Locks API](/reference/capabilities/web-locks/), for coordinating work between tabs once a user goes idle
- [PWAs on Firefox](/reference/platforms/firefox/)
- [Idle Detection compatibility data](/compatibility/idle-detection/)
- [Idle Detection API: start() method](https://wicg.github.io/idle-detection/#api-idledetector-start) (wicg.github.io)
- [Idle Detection API: requestPermission() method](https://wicg.github.io/idle-detection/#api-idledetector-requestpermission) (wicg.github.io)
- [IdleDetector browser compatibility](https://developer.mozilla.org/en-US/docs/Web/API/IdleDetector#browser_compatibility) (developer.mozilla.org)