本文主要是介绍记一次统计用户浏览网站的时长,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
项目需求:统计用户浏览该网站的时长
初始方案:只需要在根入口的的组件被销毁的时候通过axios请求接口,提交时间给后台,在实际测试的时候发现,请求还没发送过去就被取消,使用axios请求,是异步请求,导致页面卸载时,请求被取消。
解决方案:换成同步事件
<template><div id="app"><router-view/></div>
</template>
<script>import server_url from '../static/server.js'
import axios from "axios";
import { exists, constants } from "fs";
export default {data() {return {openTime: "",account: "",startDate: performance.now() // 获取当前时间的毫秒数};},mounted() {const that = this;this.account = this.$route.query.account;console.log(that.startDate, "that.that.startDate",this.account);//初始原因使用axios请求,是异步请求,导致页面卸载时,请求被取消window.onbeforeunload = function(e) {that.openTime = (performance.now() - that.startDate) / 1000;console.log(that.openTime, "that.openTime");var data = {account: that.account,date: that.changeDateTime(new Date()),openTime: parseInt(that.openTime)};//发送同步请求var oReq = new XMLHttpRequest();oReq.open("POST",`${server_url}/putuan/v1/dealer/browse/time`,false); // 同步请求oReq.setRequestHeader("Content-type", "application/json");oReq.send(JSON.stringify(data));};},created() {},methods: {changeDateTime(time) {const that = this;var date = new Date(time);var month = that.addZore(date.getMonth() + 1);var time =that.addZore(date.getHours()) +":" +that.addZore(date.getMinutes()) +":" +that.addZore(date.getSeconds());var dateStr =date.getFullYear() +"-" +month +"-" +that.addZore(date.getDate()) +" " +time;console.log(dateStr, "date");return dateStr;},addZore(value) {return ("0" + value).slice(-2);}}
};
</script>
这篇关于记一次统计用户浏览网站的时长的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!