stayEvent.ts
2.11 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
/*
* @Author: yangming yangming@didihu.com.cn
* @Date: 2023-11-30 14:46:13
* @LastEditors: yangming yangming@didihu.com.cn
* @LastEditTime: 2023-12-20 21:16:49
* @FilePath: \glsx-tracker-javascript\src\modules\stayEvent.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import type { StayDescriptor } from '../types/stay'
import collect from './collect'
import Events from './events'
class StayEvent extends Events {
static instance: StayEvent | undefined
_options: any
start_time: number = Date.now()
timeout_time: number = 1000
timer: NodeJS.Timeout | undefined
interval_time: number = 5000
/**
* 获取视口位置
*/
getPosition(): number {
let position = document.documentElement.scrollTop || document.body.scrollTop
return +position.toFixed(2)
}
/**
* 获取停留时间
*/
getStayTime(): number {
let duration = (Date.now() - this.start_time) / 1000
if (duration < 0) {
duration = 0
}
return +duration.toFixed(2)
}
/**
* 获取停留事件的数据
*/
getStayInfo(): StayDescriptor {
const position = this.getPosition()
const duration = this.getStayTime()
return {
position,
duration
}
}
/**
* 开启监听停留事件
* params
*/
trigger(this: StayEvent) {
this.addEvent(window, 'scroll', (e: MouseEvent) => {
if (this._options.collect_url && !this._options.collect_url()) {
return false
}
if (Date.now() - this.start_time < this._options.delay_time) {
return false
}
if (!this.timer) {
const para = this.getStayInfo()
this.timer = setTimeout(() => {
this.send(para)
}, this.timeout_time)
}
})
}
/**
* 发送数据
*/
send(para: object) {
this.timer = undefined
this.start_time = Date.now()
collect.getStayEvent(para)
}
/**
* 初始化
* params data初始化数据
*/
init<T>(data: T) {
this._options = data
this.trigger()
}
}
export default new StayEvent()