Web API
web-apis;Geolocation、Storage 等。
25 分钟
Web API
除 DOM 与 fetch 外,现代浏览器提供大量 Web API:地理定位、本地存储、通知、剪贴板、文件访问等。跨平台前端里,PWA 与混合壳 往往先问「Web API 够不够」,再决定是否上 Electron/Tauri。
学习目标
- 归类常用 Web API 与权限模型
- 区分 Storage、IndexedDB、Cache 的适用场景
- 对照路线图 web-apis 节点
按场景分类
| 场景 | API | 备注 |
|---|---|---|
| 持久化小数据 | localStorage / sessionStorage | 同步、有大小上限;勿存敏感 token |
| 结构化离线数据 | IndexedDB | 异步、可存对象;SW + IDB 常见组合 |
| 网络 | fetch、WebSocket | 见 http-protocol-essentials |
| 位置 | Geolocation | 需用户授权;HTTPS |
| 通知 | Notifications + Push(+ SW) | 平台差异大,iOS 限制多 |
| 设备方向/运动 | DeviceOrientation 等 | 移动端传感器 |
| 文件 | <input type="file">、FileReader | 桌面 Electron 可扩展为完整 FS |
权限:敏感 API 走 Permissions API 或浏览器弹窗;拒绝后要有降级 UI,不能假设「一定能拿到」。
Storage 选型
sessionStorage → 单标签会话(刷新可能清)
localStorage → 长期 KV,简单偏好设置
IndexedDB → 离线课程列表、草稿队列
Cache Storage → SW 控制的 HTTP 响应副本(见 cpf-sw)
与 react-essentials 状态管理分工:React state 管 UI 会话;IDB 管跨刷新持久化;不要把大对象全塞 localStorage。
Geolocation 示例
if (!navigator.geolocation) return;
navigator.geolocation.getCurrentPosition(
(pos) => console.log(pos.coords.latitude, pos.coords.longitude),
(err) => console.warn(err.code, err.message),
{ enableHighAccuracy: false, timeout: 8000 }
);
仅当产品 真的需要 位置时再请求——html-css-essentials 的可访问性与隐私意识同样适用。
与桌面壳的边界
| Web API 够用 |
|---|