# 通知触发器（showTrigger）

> Chrome 的 Notification Triggers 提案在标志之后给 showNotification() 增加了什么、showTrigger 选项与 TimestampTrigger 类，以及开发为何终止。

通知触发器是 Chrome 曾提出的定时通知方案，打算让浏览器在指定时间显示持久通知，无需打开页面，也无需推送消息。调用 `showNotification()` 时，在 `showTrigger` 选项中传入 `TimestampTrigger` 就能指定时间。Chrome 文档已声明停止开发；实现仍需开启实验性标志，Chrome Platform Status 记录 Firefox 与 WebKit 没有表态，MDN 的 `showNotification()` 参考页也没有列出 `showTrigger`。

## 语法

```js
registration.showNotification(title, { showTrigger: new TimestampTrigger(timestamp) })
registration.getNotifications({ includeTriggered: true })
```

两种形式只存在于开启了 `chrome://flags/#enable-experimental-web-platform-features` 的 Chromium 中（[Notification Triggers](https://developer.chrome.com/docs/web-platform/notification-triggers)，developer.chrome.com）。该特性在 Chrome Platform Status 上的状态为「In developer trial (Behind a flag)」（[chromestatus.com](https://chromestatus.com/feature/5133150283890688)）；Chrome 为它运行过的 origin trial 之后没有正式发布。

## 参数

| 参数 | 类型 | 含义 |
|---|---|---|
| `showTrigger` | `TimestampTrigger` | 显示通知的时刻。构造函数接受以毫秒计的 `DOMTimeStamp`，可通过 `trigger.timestamp` 读回。 |
| `includeTriggered` | boolean，`getNotifications()` 的选项 | 把尚未显示的已安排通知也包含进来，以便页面列出或用 `notification.close()` 取消它们。默认 `false`。 |

提案还讨论过为被取消的触发器触发 `notificationclose`，以及对触发时刻能提前多远设限；两者都未写入规范。

## 异常

无。

## 平台可用性

没有浏览器发布该选项。Chromium 以上述状态把实现留在实验性特性标志之后；Chrome Platform Status 记录 Firefox 与 WebKit 没有表态，MDN 对 `showNotification()` 的参考列出 `actions`、`badge`、`body`、`data`、`dir`、`icon`、`image`、`lang`、`navigate`、`renotify`、`requireInteraction`、`silent`、`tag`、`timestamp` 与 `vibrate`，其中没有 `showTrigger`。公开的停止原因是无法跨平台提供一致、可靠的行为，这与限制[周期性后台同步](/zh/reference/notifications/periodic-background-sync/)的是同一个约束。

## 示例

定时触发和取消触发都需要开启标志。生产环境要在服务端安排通知。

### 在标志之后安排一条提醒

开启标志后，触发器只是多出来的一个选项。`tag` 让后续调用替换已安排的通知，而不是再加一条。

```js
async function scheduleReminder(registration, when, title) {
  await registration.showNotification(title, {
    tag: `reminder-${when}`,
    body: '10 分钟后开始',
    showTrigger: new TimestampTrigger(when - 10 * 60 * 1000),
  });
}
```

调用只会存下请求。Chrome 文档说明，在桌面端只有 Chrome 正在运行时触发器才会触发，在 Android 上则无此限制。

### 取消已安排的通知

`getNotifications({ includeTriggered: true })` 把已安排的条目和已显示的一并返回；在触发之前关闭其中一条就是取消。

```js
async function cancelReminder(registration, when) {
  const pending = await registration.getNotifications({ includeTriggered: true });
  for (const notification of pending) {
    if (notification.tag === `reminder-${when}`) notification.close();
  }
}
```

未开启标志时，浏览器忽略选项对象，`pending` 只包含已显示的通知，循环找不到可取消的条目。

### 检测该选项并退回服务端调度

测试方法是 `'showTrigger' in Notification.prototype`，在未开启下文所述实验性标志的环境中都是 `false`，所有正式发布的浏览器默认如此。兜底做法是把计划存在服务端，再用 Web Push 投递；解释文档指出精确时刻的投递无法保证，因为网络连接和设备休眠都可能造成延迟。

```js
async function remindAt(registration, when, title) {
  if ('showTrigger' in Notification.prototype) {
    return registration.showNotification(title, { showTrigger: new TimestampTrigger(when) });
  }
  // 不开标志的浏览器都不支持：在服务端调度，用 Web Push 投递
  await fetch('/api/reminders', { method: 'POST', body: JSON.stringify({ when, title }) });
}
```

服务端调度要求投递时有网络连接。提案想消除这个限制，因此仍不时有人提出这项需求。

:::note
在 Chromium 中，`showTrigger` 与 `TimestampTrigger` 由 `NotificationTriggers` 运行时特性控制，`runtime_enabled_features.json5` 把它标为 `experimental`（[notification_options.idl](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/notifications/notification_options.idl)、[runtime_enabled_features.json5](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/platform/runtime_enabled_features.json5)，chromium.googlesource.com）。实验性特性通过 `chrome://flags/#enable-experimental-web-platform-features` 开启。没有开启时，`showTrigger` 不是选项字典的成员，所以 `'showTrigger' in Notification.prototype` 为 `false`，`TimestampTrigger` 未定义，所以 `new TimestampTrigger(...)` 会在 `showNotification()` 运行之前抛出 `ReferenceError`。如果选项对象仍带有 `showTrigger`，`showNotification()` 会像 Web IDL 对未定义的字典成员那样忽略它，通知立即显示。Chrome Platform Status 把该特性列为「In developer trial (Behind a flag)」（[chromestatus.com](https://chromestatus.com/feature/5133150283890688)）。
:::

## 另请参阅

- [Notification Triggers](https://developer.chrome.com/docs/web-platform/notification-triggers)（developer.chrome.com）
- [Notification Triggers explainer](https://github.com/beverloo/notification-triggers)（github.com）
- [Chrome Platform Status: Notification Triggers](https://chromestatus.com/feature/5133150283890688)（chromestatus.com）
- [Web Push 与 PushManager.subscribe()](/zh/reference/notifications/web-push/)
- [用于内容更新的周期性后台同步](/zh/reference/notifications/periodic-background-sync/)
- [Notifications API](/zh/reference/notifications/notifications-api/)