PWA 相关 API 总览
约 788 字大约 3 分钟
PWAAPI
2026-04-08
除了 Service Worker、Cache、Notification 三大核心之外,PWA 还可以组合一系列 Web API 来接近原生体验。本文按用途速查。
后台能力
Background Sync
用户离线时发起请求,等网络恢复后自动重试。需要 SW 配合。
// 页面
const reg = await navigator.serviceWorker.ready;
await reg.sync.register('sync-comments');
// SW
self.addEventListener('sync', (event) => {
if (event.tag === 'sync-comments') {
event.waitUntil(uploadPendingComments());
}
}仅 Chromium 支持,Firefox/Safari 尚未实现。失败会自动重试,最多几次。
Periodic Background Sync
周期性后台同步(比如每天更新一次新闻):
const status = await navigator.permissions.query({ name: 'periodic-background-sync' });
if (status.state === 'granted') {
await reg.periodicSync.register('update-news', {
minInterval: 24 * 60 * 60 * 1000
});
}需要 PWA 已被 "安装" 且用户参与度达标,浏览器才会真正触发。
Background Fetch
适合大文件下载/上传(电影、大压缩包),即使关闭页面也能继续:
const reg = await navigator.serviceWorker.ready;
const bgFetch = await reg.backgroundFetch.fetch(
'my-video',
['/videos/big.mp4'],
{
title: '下载中',
icons: [{ src: '/icons/192.png', sizes: '192x192', type: 'image/png' }],
downloadTotal: 100 * 1024 * 1024
}
);
// SW
self.addEventListener('backgroundfetchsuccess', (event) => {
event.waitUntil((async () => {
const cache = await caches.open('downloads');
const records = await event.registration.matchAll();
await Promise.all(records.map(async (r) => {
const res = await r.responseReady;
await cache.put(r.request, res);
}));
})());
});存储
| API | 场景 | 容量 |
|---|---|---|
| Cache Storage | Request/Response | 按配额(一般 ≥ 几百 MB) |
| IndexedDB | 结构化数据、离线数据库 | 按配额 |
| localStorage | 简单字符串键值(同步) | ~5 MB |
| File System Access API | 读写本地文件 | 用户授权的文件 |
| OPFS (Origin Private File System) | 高性能私有文件系统 | 按配额 |
存储配额
const { quota, usage, usageDetails } = await navigator.storage.estimate();持久化存储
const persisted = await navigator.storage.persist();设备能力
Web Share API
调用系统原生分享面板:
if (navigator.share) {
await navigator.share({
title: document.title,
text: '推荐阅读',
url: location.href,
files: [pngFile] // 可选,分享文件
});
}Web Share Target
接收 其他 App 分享过来的内容,需要在 manifest 声明:
{
"share_target": {
"action": "/share",
"method": "POST",
"enctype": "multipart/form-data",
"params": {
"title": "title",
"text": "text",
"url": "url",
"files": [{ "name": "images", "accept": ["image/*"] }]
}
}
}Clipboard API
await navigator.clipboard.writeText('hello');
const text = await navigator.clipboard.readText();
// 读写图片
const items = await navigator.clipboard.read();
for (const item of items) {
if (item.types.includes('image/png')) {
const blob = await item.getType('image/png');
}
}Geolocation
navigator.geolocation.getCurrentPosition(
(pos) => console.log(pos.coords.latitude, pos.coords.longitude),
(err) => console.error(err),
{ enableHighAccuracy: true, timeout: 5000 }
);Media Devices
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
document.querySelector('video').srcObject = stream;Device Sensors
DeviceMotionEvent/DeviceOrientationEventAccelerometer、Gyroscope、Magnetometer(Generic Sensor API)AmbientLightSensor
Web Bluetooth
const device = await navigator.bluetooth.requestDevice({
filters: [{ services: ['heart_rate'] }]
});Web USB / Web Serial / Web HID
与 USB 设备、串口、游戏手柄等硬件通信,常用于工业工具 PWA。
Wake Lock
防止屏幕息屏(视频播放、演示文稿):
let lock = null;
try {
lock = await navigator.wakeLock.request('screen');
} catch (e) { /* 被系统中断 */ }
document.addEventListener('visibilitychange', async () => {
if (document.visibilityState === 'visible' && !lock) {
lock = await navigator.wakeLock.request('screen');
}
});Badging API
在桌面/任务栏图标上显示小红点:
navigator.setAppBadge(5); // 显示数字 5
navigator.clearAppBadge();File Handling
让 PWA 成为某类文件的默认打开程序:
{
"file_handlers": [
{
"action": "/open",
"accept": { "text/markdown": [".md"] }
}
]
}Protocol Handlers
注册自定义协议(如 web+kb://):
{
"protocol_handlers": [
{ "protocol": "web+kb", "url": "/handle?q=%s" }
]
}Window Controls Overlay
桌面 PWA 接管标题栏区域,实现自定义窗口控件:
{ "display_override": ["window-controls-overlay"] }兼容性速查
| API | Chrome | Safari | Firefox |
|---|---|---|---|
| Service Worker / Cache | ✅ | ✅ | ✅ |
| Notification / Push | ✅ | ✅(16.4+) | ✅ |
| Background Sync | ✅ | ❌ | ❌ |
| Periodic Background Sync | ✅ | ❌ | ❌ |
| Background Fetch | ✅ | ❌ | ❌ |
| Web Share | ✅ | ✅ | 部分 |
| Badging | ✅(桌面) | 部分 | ❌ |
| File System Access | ✅ | ❌ | ❌ |
| Web Bluetooth/USB/HID | ✅ | ❌ | ❌ |
生产环境使用前务必在 Can I Use 核对最新兼容性,并做好能力检测与降级。
