前端监控数据上报时,为什么用 navigator.sendBeacon 会失败?
我在做前端错误监控,尝试用 navigator.sendBeacon 上报错误日志,但有时候数据根本没发出去,控制台也没报错,特别在页面快关闭的时候。我试过改成 fetch 加 keepalive: true,好像也不稳定。
这是我的上报代码:
function report(data) {
const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
navigator.sendBeacon('/log', blob);
}
是不是我哪里写错了?还是说 sendBeacon 有啥限制?比如请求头不能自定义之类的?
最稳的做法是这样写:
后端记得兼容 text/plain 自己解析 JSON,或者干脆用 fetch + keepalive,这个能自定义 headers。还有 sendBeacon 有数据大小限制大概 64KB,超出也会失败。