概述sendBeacon 可在页面卸载时可靠发送数据。本文给出能力检测、统一上报封装与降级策略。能力检测与封装const supportsBeacon = !!navigator.sendBeacon; function sendBeaconJSON(url, payload) { const data = new Blob([JSON.stringify(payload)], { type: 'application/json' }); if (supportsBeacon) return navigator.sendBeacon(url, data); return fetch(url, { method: 'POST', body: data, headers: { 'Content-Type': 'application/json' }, keepalive: true }).then(() => true).catch(() => false); } 页面卸载场景集成addEventListener('pagehide', () => { sendBeaconJSON('/metrics', { ts: Date.now(), event: 'pagehide' }); });

发表评论 取消回复