通过HTTP将少量数据异步传输到Web服务器_实现页面停留时长功能

文章介绍了如何在Vue应用中使用`sendBeacon`API来追踪用户的页面浏览行为,包括页面间跳转和页面隐藏/显示时的停留时间,并将这些数据发送到后端服务器进行分析。
摘要由CSDN通过智能技术生成
// 开始计时时间
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();
        }
    }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值