<SKYLER/>
【前端监控】如何确保页面关闭后,数据上报请求不会取消
Back to Blog
August 12, 2022(updated June 29, 2024)前端监控

🪅【前端监控】如何确保页面关闭后,数据上报请求不会取消

在做前端监控数据上报的时候,当页面关闭后,发出去的请求会被取消掉,如下图:

request-canceled.webp

页面跳转到Other Page导致在Main Page发送的请求被取消了

解决办法

  1. 将fetch api的keepalive参数设置成true
fetch("/log", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      some: "data"
    }),
    keepalive: true
});
  1. 使用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/