前端埋点 sendBeacon 替代方式

看英文文档真的很重要

sendBeacon 限制比较多, 容易跨域, 跨域时候还必须指定请求头, 不能使用通配符来解决跨域

文档地址

文档里面说 fetch 其实可以代替 sendBeacon

原文:
Note: For use cases that need the ability to send requests with methods other than POST, or to change any request properties, or that need access to the server response, instead use the fetch() method with keepalive set to true.

只需要给fetch设置 keepalive: true

fetch(url, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
    },
    keepalive: true,
  }).catch((err) => {
    console.error('HexAnalysis api error!', err)
  })

你可能感兴趣的:(前端)