关闭/刷新 网页时发送请求

Arthur
2023-07-26 / 0 评论 / 65 阅读 / 正在检测是否收录...

关闭/刷新 网页时发送请求

有时候我们需要在用户离开页面的时候,做一些上报来记录用户行为。又或者是发送服务器ajax请求,通知服务器用户已经离开,比如直播间内的退房操作。

这里涉及到Window: beforeunload event

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page. If the user confirms, the browser navigates to the new page, otherwise it cancels the navigation.

注意:Sticky activation is required. The user has to have interacted with the page in order for this feature to work.

发送移步请求会被浏览器abort ,有下面两种解决办法

Navigator: sendBeacon() method

会发送一个post 的fetch请求,及时浏览器关闭也会发出去,但是有64kb限制,而且只能在beforeunload 或者visibilitychange 中使用
其他事件中回调,会丢失数据。
只能发送post请求,无法自定义请求头

sendBeacon(url)
sendBeacon(url, data)

fetch 请求,keepalive

The keepalive option can be used to allow the request to outlive the page. Fetch with the keepalive flag is a replacement for the Navigator.sendBeacon() API.
标记keepalive的fetch请求允许在页面卸载后执行。

const data = JSON.stringify({
   time: performance.now()
 });

fetch(url, {
 method: 'POST',
 body: data,
 headers: {
  'Content-Type': 'application/json'
 },
 keepalive: true,
});
0
如果你觉得文章还不错,可以请我喝杯咖啡啊哈哈哈
wechat alipay

评论 (0)

取消