`title: Beacon API 可靠日志上报与持久化回退``categories: Web 开发/前端/数据管理``keywords: Beacon API,keepalive,日志,持久化,IndexedDB``description: 使用 Beacon API 在卸载阶段可靠上报日志与统计,失败或不支持时回退到 IndexedDB 队列与下次会话重放,提升采集稳定性。`上报与回退function sendBeaconJSON(url, data) { const blob = new Blob([JSON.stringify(data)], { type: 'application/json' }); const ok = navigator.sendBeacon(url, blob); return ok; } async function enqueueIfFail(db, url, data) { const ok = sendBeaconJSON(url, data); if (!ok) { await new Promise((resolve, reject) => { const tx = db.transaction('beacons', 'readwrite'); tx.objectStore('beacons').put({ id: crypto.randomUUID(), url, data, ts: Date.now() }); tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error); }); } }

发表评论 取消回复