// 开始计时时间
let startTime;
// 结束计时时间
let endTime;
let toRoute;
const sendBeacon = (url, data = {}) => {
const blob = new Blob([JSON.stringify(data)], {
type: 'application/json; charset=UTF-8',
});
return navigator.sendBeacon(url, blob);
};
router.afterEach((to, from) => {
endTime = Date.now();
if (from.name && from.name !== 'login') {
const user = sessionStorage.getItem('userInfo');
const userId = JSON.parse(user).userId;
// console.log('用户由 ', from.name, ' 页面 跳转到 ', to.name, ' 页面,在 ', from.name, ' 页面停留了 ', currentTime - startTime, '毫秒。转换成秒数约为:', parseInt(String((currentTime - startTime) / 1000)))
const stayTime = endTime - startTime;
sendBeacon(process.env.VUE_APP_API_URL + '/oauth/xx/xxx', {
userId: userId,
menuUrl: from.fullPath,
activeTime: '',
stayTime: String(stayTime / 1000)
});
}
if (to && to.name !== 'login') {
const user = sessionStorage.getItem('userInfo');
const userId = JSON.parse(user).userId;
sendBeacon(process.env.VUE_APP_API_URL + '/oauth/xx/xx', {
userId: userId,
menuUrl: to.fullPath,
action: 'enter'
});
}
startTime = Date.now();
toRoute = to;
})
document.addEventListener('visibilitychange', () => {
if (toRoute.name !== 'login') {
if (document.hidden) {
endTime = Date.now();
const stayTime = endTime - startTime;
const user = sessionStorage.getItem('userInfo');
const userId = JSON.parse(user).userId;
sendBeacon(process.env.VUE_APP_API_URL + '/oauth/xx/xx', {
userId: userId,
menuUrl: toRoute.fullPath,
activeTime: '',
stayTime: String(stayTime / 1000)
});
} else {
startTime = Date.now();
}
}
})
通过HTTP将少量数据异步传输到Web服务器_实现页面停留时长功能
于 2023-12-25 09:08:05 首次发布
文章介绍了如何在Vue应用中使用`sendBeacon`API来追踪用户的页面浏览行为,包括页面间跳转和页面隐藏/显示时的停留时间,并将这些数据发送到后端服务器进行分析。
摘要由CSDN通过智能技术生成