前言

有时候,在做页面统计的时候,会需要在浏览器关闭页面的时候之前发送一个http请求。
例如在直播页面之中统计观看直播人数的时候,进入的时候发送一个进入房间的请求,离开的时候同时也要发送一个离开的请求。

unload与beforeunload

浏览器里有两个事件是关于页面关闭的,那就是unload与beforeunload。

MDN中关于beforeunload和unload的介绍:

当浏览器窗口关闭或者刷新时,会触发beforeunload事件。当前页面不会直接关闭,可以点击确定按钮关闭或刷新,也可以取消关闭或刷新。 当文档或一个子资源正在被卸载时, 触发unload事件。

  1. window.addEventListener("beforeunload", function (event) {
  2. // Cancel the event as stated by the standard.
  3. event.preventDefault();
  4. // Chrome requires returnValue to be set.
  5. event.returnValue = '';
  6. });

Navigator.sendBeacon

其实发送http请求有很多种方法,如发送同步或者异步的xhr、fetch,这些方法中或多或少都会有一些不足。
在使用同步的xhr请求的时候,由于阻塞发送需要时间,用户需要等待发送完成后才能进入新的页面(直接关掉标签,那不是凉了吗~),会带来不太好的体验。
于是,便有了sendBeacon。

MDN中关于sendBeacon的描述:

这个方法主要用于满足统计和诊断代码的需要,这些代码通常尝试在卸载(unload)文档之前向web服务器发送数据。过早的发送数据可能导致错过收集数据的机会。然而,对于开发者来说保证在文档卸载期间发送数据一直是一个困难。因为用户代理通常会忽略在 [unload](https://developer.mozilla.org/zh-CN/docs/Web/Reference/Events/unload) 事件处理器中产生的异步 XMLHttpRequest。

window.addEventListener('unload', logData, false);

function logData() {
  navigator.sendBeacon("/log", analyticsData);
}

实现

在React中实现代码如下:

componentDidMount() {
    // 为了确保发送 同时监听了两个事件
    window.addEventListener('beforeunload', this.sendBeacon);
    window.addEventListener('unload', this.sendBeacon);
}

sendBeacon = event => {
    // Cancel the event as stated by the standard.
    event.preventDefault();
    // Chrome requires returnValue to be set.
    event.returnValue = '';

    let blob = new Blob([`room_id=123`], { type: 'application/x-www-form-urlencoded' });
    navigator.sendBeacon('/api/someRequestsUrl', blob);
};

参考资料

Navigator.sendBeacon