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
| class PageTracker {
constructor() {
this.currentPage = null
this.pageStartTime = null
this.init()
}
init() {
// 页面加载完成
window.addEventListener('load', () => {
this.trackPageView()
})
// SPA路由变化
this.trackRouteChanges()
}
trackPageView() {
this.pageStartTime = Date.now()
this.currentPage = {
url: window.location.pathname,
referrer: document.referrer,
title: document.title,
timestamp: this.pageStartTime
}
this.sendEvent('pageview', this.currentPage)
}
trackRouteChanges() {
// 监听路由变化(需要根据具体框架实现)
let lastUrl = location.href
new MutationObserver(() => {
const url = location.href
if (url !== lastUrl) {
lastUrl = url
this.trackPageView()
}
}).observe(document, { subtree: true, childList: true })
}
trackEvent(category, action, label, value) {
this.sendEvent('event', {
category,
action,
label,
value,
timestamp: Date.now()
})
}
sendEvent(type, data) {
// 发送到分析服务器
fetch('/api/analytics', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
type,
data,
userId: this.getUserId(),
sessionId: this.getSessionId()
})
})
}
}
|