在做前端监控数据上报的时候,当页面关闭后,发出去的请求会被取消掉,如下图:
页面跳转到Other Page导致在Main Page发送的请求被取消了
解决办法
- 将fetch api的keepalive参数设置成true
fetch("/log", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
some: "data"
}),
keepalive: true
});
- 使用Navigator.sendBeacon()
const blob = new Blob([JSON.stringify({ some: "data" })], { type: 'application/json; charset=UTF-8' });
navigator.sendBeacon('/log', blob));
区别
fetch api:
- 任务优先级是
高
- 可以自定义请求头
- 支持get请求方式,不仅仅只是post请求
Navigator.sendBeacon()
- 任务优先级是
低
- 不支持get请求,也不能自定义请求头
在前端监控中推荐使用Navigator.sendBeacon()
,因为不会和主任务竞争资源。
参考文章:https://css-tricks.com/send-an-http-request-on-page-exit/