# 进阶

> 以渐进增强方式接入推送、文件访问与平台集成等生产级能力，每一步都先做兼容性检查。

Web Push、文件访问、后台同步和图标角标可以增强应用功能，但要先确认浏览器是否支持。不支持某项能力时，页面仍应能用。先写好回退分支，再加增强功能和特性检测，发布前查清兼容性。先完成[入门](/zh/guides/getting-started/)、[让它可安装](/zh/guides/installable/)与[离线策略](/zh/guides/offline/)；这些能力要求已注册 Service Worker，且 manifest 可安装。

## 把能力闸门只写一次

把检测集中在一个模块里，让界面、Service Worker 和埋点使用同一份能力判断。读取对象图来检测支持情况，无需判断 User-Agent。为每项能力提供回退操作，让按钮仍然能用。

```js
export const capabilities = {
  push: 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window,
  fileSystemAccess: 'showOpenFilePicker' in window,
  backgroundSync: 'serviceWorker' in navigator && 'SyncManager' in window,
  badging: 'setAppBadge' in navigator,
};

export const fallbacks = {
  push: () => showEmailDigestOptIn(),            // 用服务端邮件摘要代替推送
  fileSystemAccess: () => showDownloadAndUpload(), // <a download> 加 <input type="file">
  backgroundSync: () => retryQueueOnNextLoad(),    // 在 'online' 事件时冲刷 IndexedDB 队列
  badging: () => showUnreadCountInTitle(),         // document.title = `(3) Field Notes`
};

export function withCapability(name, enhanced) {
  return capabilities[name] ? enhanced() : fallbacks[name]();
}
```

iOS Safari 标签页里虽然有 `PushManager`，WebKit 却只允许主屏幕 Web 应用使用推送（iOS 与 iPadOS 16.4，2023-03）。所以检测到 API 存在，还不能证明用户能用这项功能。查对应的兼容性条目时，要读清备注中的限制。

## 在用户手势之后接入 Web Push

按 web.dev 的推送概览，客户端请求权限并订阅，服务端发送推送，Service Worker 接收推送并显示通知。权限请求必须跟在点击之类的手势之后；WebKit 对主屏幕 Web 应用的要求相同。用你的 VAPID 公钥订阅（web.dev："the combination of the private and public key is known as the application server keys"）：

```js
async function enablePush(vapidPublicKey) {
  if (!capabilities.push) return fallbacks.push();
  const permission = await Notification.requestPermission();
  if (permission !== 'granted') return fallbacks.push();
  const registration = await navigator.serviceWorker.ready;
  const subscription = await registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: vapidPublicKey,
  });
  await fetch('/api/push/subscribe', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(subscription),
  });
}
```

订阅对象中的 `endpoint` 指向浏览器厂商的推送服务；web.dev 把它的域名描述为 "essentially the push service"，路径则是客户端标识。把整个订阅对象存在服务端，发送返回 404 或 410 时删除它。在 Service Worker 里，`push` 监听器调用 `self.registration.showNotification()`；收到推送却不显示通知就属于静默推送，浏览器不允许这样做。

## 用同样的方式守护文件访问与后台同步

`showOpenFilePicker()` 让编辑器类应用读写用户选中的文件；回退时，用 `<input type="file">` 读取，用 `<a download>` 写入，两者在各浏览器中都受支持。Background Sync 让 worker 在网络恢复时重放离线期间的写入；回退是把队列放在 IndexedDB 里，在 `online` 事件或下次页面加载时提交队列。两者都调用 `withCapability()`，把两个分支放在一起，修改增强功能时也能检查回退路径。

## 在 DevTools 中测试增强路径

Chrome 的 **Service workers** 面板有 **Push** 与 **Sync** 链接，无需服务器即可向活动 worker 派发 `push` 与 `sync` 事件，让你在后端尚不存在时先验证接收侧。用 **Offline** 确认排队的写入在刷新后仍在，并在取消勾选后重新提交。

:::caution
Chrome DevTools 中 **Push** 链接旁的 **Push data** 输入框默认是纯文本载荷 `Test push message from DevTools`。字符串 `testPushMessageFromDevtools` 及使用它的 `push-data` 设置定义在 DevTools 前端的 [`front_end/panels/application/ServiceWorkersView.ts`](https://github.com/ChromeDevTools/devtools-frontend/blob/main/front_end/panels/application/ServiceWorkersView.ts)（main 分支）。直接解析 `event.data.json()` 的 `push` 处理器会在这个载荷上抛错，因为它是纯文本。先读 `event.data.text()`，或给 JSON 解析加保护。
:::

## 另请参阅

- [Web Push](/zh/reference/notifications/web-push/)
- [File System Access](/zh/reference/capabilities/file-system-access/)
- [Background Sync](/zh/reference/service-worker/background-sync/)
- [角标](/zh/reference/installation/badging/)
- [按特性查看兼容性](/zh/compatibility/by-feature/)
- [Push notifications overview](https://web.dev/articles/push-notifications-overview)（web.dev）
- [Web Push for Web Apps on iOS and iPadOS](https://webkit.org/blog/13878/web-push-for-web-apps-on-ios-and-ipados/)（webkit.org）

← 返回[指南](/zh/guides/)总览。