viewEvent.ts
3.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
* @Author: yangming yangming@didihu.com.cn
* @Date: 2023-11-30 14:45:53
* @LastEditors: yangming yangming@didihu.com.cn
* @LastEditTime: 2023-12-14 17:36:55
* @FilePath: \glsx-tracker-javascript\src\modules\viewEvent.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import type { viewBase, routerOption } from '../types/view'
import Events from './events'
import utils from '../utils/helper'
import collect from './collect'
class ViewEvent {
baseParams: viewBase
last_time:string
routerModel: routerOption | undefined = 'hash'
/**
* 初始化页面信息
*$page_title: 页面标题
$page_url: 页面地址
$page_path: 页面地址
$path_href: 页面完整地址
$enter_time: 进入页面的时间
$leave_time:离开页面的时间
$page_referrer: 页面来源
*/
constructor() {
this.last_time = utils.dateFormat(new Date())
this.baseParams = {
$page_title: document.title,
$page_url: location.href,
$page_path: location.pathname,
$enter_time: this.last_time,
$leave_time: '',
$page_referrer: ''
}
}
/**
* 初始化
*/
init(routerModel?: routerOption) {
this.routerModel = routerModel
this.initEvent()
}
/**
* 重写pushState/replaceState事件
*/
initEvent() {
window.history['pushState'] = this.createHistoryEvent('pushState')
window.history['replaceState'] = this.createHistoryEvent('replaceState')
if (this.routerModel == 'history') {
this.captureEvents(['pushState', 'replaceState', 'popstate'])
}
if (this.routerModel == 'hash') {
this.captureEvents(['hashchange'])
}
}
/**
* 绑定hashchange、popstate事件
*/
captureEvents<T>(MouseEventList: string[]) {
MouseEventList.forEach(event => {
Events.addEvent(window, event, (e: MouseEvent) => {
this.trigger()
})
})
}
/**
* 创建事件
* params history事件名
*/
createHistoryEvent = <T extends keyof History>(type: T): (() => any) => {
const origin = history[type]
const self = this
return function (this: any) {
const res = origin.apply(this, arguments)
self.trigger()
return res
}
}
/**
* 修改页面信息、并合并自定义属性
* @param customProps 自定义属性
*/
getPresetProperties(customProps: any) {
const current_url = location.href
this.baseParams.$page_referrer = this.baseParams.$page_url
this.baseParams.$page_url = current_url
const current_time = utils.dateFormat(new Date())
this.baseParams.$leave_time = current_time
this.baseParams.$enter_time = this.last_time;
this.last_time = current_time
let _customProps = typeof customProps === 'object' && customProps !== null ? customProps : {}
return Object.assign(this.baseParams, _customProps)
}
/**
* 绑定浏览事件
*/
trigger(prop?: any) {
const para = this.getPresetProperties(prop)
collect.getViewEvent(para)
}
}
export default new ViewEvent()