# Idle Detection API

> IdleDetector 如何报告用户与屏幕空闲状态，以及权限、阈值、策略错误和不支持时的回退处理。

`IdleDetector` 报告用户是否在指定时间内操作过设备，以及屏幕是否锁定。你可以设置至少一分钟的阈值，任一状态变化都会触发 `change` 事件。WICG 草案用 `idle-detection` 权限控制访问，并把聊天应用的在线状态提示列为使用场景。

BCD `api.IdleDetector` 记录 Chrome 94 起支持，Edge 94 至 95 版支持并从 Edge 114 起恢复，还把 Chrome 支持镜像到其列出的 Chromium 衍生浏览器。BCD 没有记录 Firefox 或 Safari 支持。[Idle Detection 兼容性数据](/zh/compatibility/idle-detection/)列出了对应的浏览器版本。

## 语法

```js
new IdleDetector()

IdleDetector.requestPermission()

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

构造函数不接受参数。`requestPermission()` 是静态方法，仅 `[Exposed=Window]`，返回 `Promise<PermissionState>`，兑现为 `"granted"`、`"denied"` 或 `"prompt"`。`start()` 返回 `Promise<undefined>`，检测器进入 `"started"` 状态后兑现。整个接口带 `[SecureContext]`，并且也暴露在专用 Worker 中：那里可以调用 `start()`，但不存在 `requestPermission()`。

## 参数

`start()` 接受一个可选的 `options` 参数，类型为 `IdleOptions` 字典。

| 成员 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `threshold` | `unsigned long long`（`[EnforceRange]`） | 否 | 无交互多少毫秒后 `userState` 变为 `"idle"`。最小值 60,000，更小的值会拒绝 Promise。负数或非有限值因 `[EnforceRange]` 在绑定层抛出 `TypeError`。 |
| `signal` | `AbortSignal` | 否 | 中止该信号会停止检测器，并以信号的中止原因拒绝尚未完结的 `start()` Promise。 |

两个只读属性保存状态：`userState` 为 `"active"` 或 `"idle"`，`screenState` 为 `"locked"` 或 `"unlocked"`。它们的初始值都是 `null`。请在 `change` 处理函数中读取变化，别把 `new IdleDetector()` 后立即读到的值当成一次检测结果。

## 异常

规范定义了以下拒绝情形。

| 方法 | 异常 | 条件 |
|---|---|---|
| `requestPermission()` | `InvalidStateError` | 文档不是 fully active。 |
| `requestPermission()` | `NotAllowedError` | 调用时没有瞬时用户激活；权限提示只能跟在点击或按键之后。 |
| `start()` | `InvalidStateError` | 文档不是 fully active，或检测器的内部状态不是 `"stopped"`（已在启动中或已启动）。 |
| `start()` | `NotAllowedError` | 文档不允许使用 `idle-detection` 这一受策略控制的特性（默认允许列表为 `'self'`），或启动检测器时 `idle-detection` 权限状态为 `"denied"`。 |
| `start()` | `TypeError` | `threshold` 小于 60,000 ms。 |
| `start()` | 信号的中止原因 | 调用 `start()` 时 `options.signal` 已中止，或 Promise 待定期间被中止。 |

Chromium 有一处偏离规范：Permissions Policy 拦截该特性时，`start()` 以 `SecurityError` 拒绝，而不是 `NotAllowedError`（见下方提示框）。`start()` 的 promise 仍未决、浏览器端监视器就断开时，Chromium 还会以 `NotSupportedError` 和消息 `Idle detection not available.` 拒绝 `start()`，规范没有定义这种情况。

根据失败阶段和异常名选择恢复操作。`requestPermission()` 因缺少瞬时用户激活而抛出 `NotAllowedError` 时，把它移进点击或按键处理函数。权限未获准时继续运行非 API 回退分支。阈值引发 `TypeError` 时，把 `threshold` 提高到至少 `60_000`。跨源 iframe 遇到策略错误时，嵌入页面可以用 `allow="idle-detection"` 委派能力；WICG 规范规定的默认允许列表是 `'self'`。

:::caution
Chromium 的 [`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）与 [`permissions_strings.grdp`](https://chromium.googlesource.com/chromium/src/+/main/components/permissions_strings.grdp)（chromium.googlesource.com）定义了以下行为。没有瞬时用户激活时调用 `IdleDetector.requestPermission()`，会以 `NotAllowedError: Must be handling a user gesture to show a permission request.` 拒绝。在 Android 与 iOS 构建中，权限提示文本为 `<origin> wants to know when you're actively using this device`（英文语言环境）；其他平台的提示在「This site would like to:」之后列出片段 `Know when you're actively using this device`。`start({ threshold: 30_000 })` 以 `TypeError: Minimum threshold is 1 minute.` 拒绝，检测器仍处于已启动状态时再次调用同一实例的 `start()`，会以 `InvalidStateError: Idle detector is already started.` 拒绝。权限被拒绝时以 `NotAllowedError: Idle detection permission denied` 拒绝。
:::

## 示例

先检测构造函数是否存在。接口缺失或权限未获准时，保留通过 `visibilitychange` 读取页面可见性的回退逻辑，不把它冒充为系统级空闲状态。

### 一分钟无操作后显示「离开」在线状态徽标

权限请求在 `click` 处理函数内运行，由它提供 `requestPermission()` 所需的瞬时激活。API 缺失时，回退逻辑在标签页隐藏时把用户标记为离开。页面可见性不报告系统级在线状态。

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

function markAway(isAway) {
  badge.textContent = isAway ? '离开' : '活跃';
}

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

回退分支仍会根据文档隐藏或显示来更新徽标，但不会把它当成设备空闲信号；权限未获准时也会启用该分支。如果实例名为 `idleDetector`，用 `await idleDetector.start()` 等待启动；状态变化仍应在事件处理函数里读取。

### 用户退出登录时用 AbortSignal 停止检测器

接口没有 `stop()` 方法。应用需要结束监视时，把 `AbortSignal` 传给 `start()`。`start()` 兑现后再中止不会改变这个已经完结的 Promise；待定期间中止则以中止原因拒绝它，因此 `catch` 要区分主动中止与其他失败。

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

`controller.abort()` 之后检测器回到 `"stopped"` 状态，同一实例可以带着新的信号再次启动；旧的 `userState` 与 `screenState` 值不再更新。

## 另请参阅

- [Screen Wake Lock API](/zh/reference/capabilities/wake-lock/)，与之互补的「阻止屏幕锁定」请求
- [Web Locks API](/zh/reference/capabilities/web-locks/)，用户空闲后协调多个标签页之间的工作
- [Firefox 上的 PWA](/zh/reference/platforms/firefox/)
- [Idle Detection 兼容性数据](/zh/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）