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

// 开始计时时间
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,服务器)