← 中文资源

简体中文版本

sendBeacon 在页面隐藏时发送

pagehide 时机用 navigator.sendBeacon 交出小载荷:浏览器保证卸载后仍会送达,普通 fetch 此刻可能被取消而丢数据。

阅读英文原文

实现说明

逻辑集中在函数 reportCartOnHide里。

使用要点

  • 这是浏览器侧代码——window、navigator 在 Node 里解析不到。
  • 演示输出是带标签的(beacon queued: $),每个操作都会留下自己的一行标注。

常见问题

「sendBeacon 在页面隐藏时发送」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(window),Node 里不存在。请在页面或 DevTools 控制台中运行。

主要签名是 function reportCartOnHide()

核心语句

const queued = navigator.sendBeacon('/api/cart-exit', JSON.stringify(cart));
window.addEventListener('pagehide', reportCartOnHide);

代码示例

// sendBeacon hands a small payload to the browser for delivery that
// survives the page unloading — the fire-and-forget channel for
// analytics, where fetch can be cancelled mid-flight
const cart = { sku: 'AB-1234', qty: 2 };

function reportCartOnHide() {
  // The boolean return only says the payload was queued for delivery,
  // not that the server has answered
  const queued = navigator.sendBeacon('/api/cart-exit', JSON.stringify(cart));
  console.log(`beacon queued: ${queued}`);
}

// pagehide fires on every kind of unload, including mobile app
// backgrounding — the reliable moment to flush
window.addEventListener('pagehide', reportCartOnHide);