前端vue收集用户行为日志(一)
1.创建用于埋点setPoint.js
import Cookies from 'js-cookie'
export default {
setPoint: function (etJson) {
//main 所属应用 cmdata 公共数据 bussdata 业务数据
const params = { main: 'pc-web', cmdata: {}, bussdata: {}}
// 获取事件时间
var myDate = new Date()
params.bussdata.ett = myDate.getTime()
params.bussdata.en = etJson.type
params.bussdata.kv = etJson.kv
// Document对象数据
if (document) {
params.cmdata.hostname = document.domain || ''
params.cmdata.url = document.URL || ''
params.cmdata.title = document.title || ''
params.cmdata.referrer = document.referrer || ''
}
// //分辨率
if (window && window.screen) {
params.cmdata.sh = window.screen.height || 0
params.cmdata.sw = window.screen.width || 0
params.cmdata.cd = window.screen.colorDepth || 0
}
// //设备信息
if (navigator) {
params.cmdata.lang = navigator.language || ''
params.cmdata.ua = navigator.userAgent || ''
// 页面加载时间
params.cmdata.loadT = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart || 0
}
const userId = '603'
params.cmdata.userId = userId
// 浏览器唯一标识
const uuid = Cookies.get('uuid')
if (uuid != null && uuid != '') {
params.cmdata.sid = uuid
} else {
const newUuid = this.generateUUID()
Cookies.set('uuid', newUuid)
params.cmdata.sid = newUuid
}
// 拼接参数串
var args = ''
for (var i in params) {
if (args != '') {
args += '&'
}
args += i + '=' + encodeURIComponent(JSON.stringify(params[i]))
}
// 通过Image对象请求后端脚本
const img = new Image(1, 1)
img.src = 'http://192.168.152.102/log.gif?' + args
},
//生成唯一的UUID
generateUUID() {
let d = new Date().getTime();
if (window.performance && typeof window.performance.now === "function") {
d += performance.now(); //use high-precision timer if available
}
let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
}
2.在main.js中添加
//这是我项目中setPoint.js的路径
import bPoint from '@/utils/setPoint';
Vue.prototype.bPoint = bPoint;
设置为全局也可在页面中直接使用
created() {
//页面每次刷新收集一次日志
//可自定义数据
/**
* type:事件
* kv: key-value 事件相关数据
*/
const eventJson = { type: 'browse', kv: { action: '1', currPage: 'documentView', docId: this.documentId }}
this.bPoint.setPoint(eventJson)
},
3.在main.js添加指令
// 埋点指令
Vue.directive('bpoint', {
bind: (el, binding, vnode) => {
el.addEventListener('click', () => {
//自定义数据
const data = binding.value;
//调用setPoint.js
bPoint.setPoint(data)
}, false);
}
})
4.进行埋点
例如:
<el-button v-bpoint="{type:'click',kv:{action:'1',docId:scope.row.documentId,cateId:scope.row.categoryId,place:3}}">详情页链接</el-button>
参考:
网站用户行为日志采集和后台日志服务器搭建
https://blog.csdn.net/sayoko06/article/details/107400859