一. 使用navigator.sendBeacon
方法:navigator.sendBeacon
是一个异步方法,用于在页面卸载时发送少量数据到服务器。它不会阻塞页面的卸载过程,适用于发送少量的埋点数据。使用方法如下:
navigator.sendBeacon('http://example.com/endpoint', JSON.stringify({key: 'value'}));
这种方法适用于发送少量的数据,并且不需要等待服务器的响应。
二. 监听visibilitychange
事件:通过监听visibilitychange
事件,可以在页面即将卸载时发送数据。当文档的可见性状态变为隐藏时,触发数据发送:
document.addEventListener('visibilitychange', function() {
if (document.visibilityState === 'hidden') {
navigator.sendBeacon('http://example.com/endpoint', JSON.stringify({key: 'value'}));
}
});
这种方法可以确保在页面关闭时发送数据,而不会影响用户体验
三. 使用onbeforeunload
和onunload
事件:这两个事件在页面卸载时会触发,可以用来发送数据。onbeforeunload
在页面卸载前触发,而onunload
在页面完全卸载后触发。可以通过设置一个时间戳来区分是刷新还是关闭页面:
let beginTime = 0;
window.onbeforeunload = function() {
beginTime = new Date().getTime();
};
window.onunload = function() {
let differTime = new Date().getTime() - beginTime;
if (differTime > 10) { // 假设关闭页面时间差大于10毫秒
navigator.sendBeacon('http://example.com/endpoint', JSON.stringify({key: 'value'}));
}
};
这种方法需要注意区分刷新和关闭页面的行为,以确保只在关闭页面时发送数据