Skip to content

sendBeacon

为什么需要 sendBeacon

传统的 XMLHttpRequest 和 Fetch API 在页面卸载时可能会导致数据丢失, sendBeacon 允许在页面卸载时异步发送数据,确保数据不会丢失, 适用于性能监控、用户行为分析等场景。

基本使用

  1. 基本语法

    js
    navigator.sendBeacon(url, data);
    • 返回一个布尔值,表示请求是否成功加入发送队列
    • data 支持的格式:
      • string
      • Blob
      • ArrayBuffer
      • FormData
      • URLSearchParams
  2. 主要特点

    • 异步发送,不阻塞页面
    • 在页面卸载时也能保证数据发送
    • 不支持响应处理
    • 自动使用 POST 方法
    • 不能设置请求头(除了 Content-Type)

使用场景

  1. 页面退出分析

    js
    window.addEventListener("unload", () => {
      navigator.sendBeacon(
        "/analytics",
        JSON.stringify({
          event: "page_exit",
          timeSpent: calculateTimeSpent(),
        })
      );
    });
  2. 性能数据上报

    js
    const performanceData = new FormData();
    performanceData.append("timing", JSON.stringify(performance.timing));
    navigator.sendBeacon("/performance", performanceData);

注意事项

  1. 数据大小限制

    • 不同浏览器有不同的限制,通常在 64KB 左右
    • 超出限制时返回 false
  2. 兼容性处理

    js
    function sendData(url, data) {
      if (navigator.sendBeacon) {
        return navigator.sendBeacon(url, data);
      }
      // 降级处理
      const xhr = new XMLHttpRequest();
      xhr.open("POST", url, false); // 同步请求
      xhr.send(data);
    }

参考资料