-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisitor-tracker.js
More file actions
146 lines (131 loc) · 4.78 KB
/
visitor-tracker.js
File metadata and controls
146 lines (131 loc) · 4.78 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// visitor-tracker.js
class VisitorTracker {
constructor(supabaseUrl, supabaseKey, options = {}) {
this.supabaseUrl = supabaseUrl;
this.supabaseKey = supabaseKey;
this.options = {
trackLocation: true,
trackDevice: true,
trackReferrer: true,
...options
};
}
async collectAndSend() {
try {
const visitorData = await this.collectVisitorData();
await this.sendVisitorData(visitorData);
} catch (error) {
console.error('Visitor tracking error:', error);
}
}
async collectVisitorData() {
const data = {
user_agent: navigator.userAgent,
page_url: window.location.href,
created_at: new Date().toISOString()
};
if (this.options.trackReferrer) {
data.referrer = document.referrer;
}
if (this.options.trackDevice) {
const ua = this.parseUserAgent(navigator.userAgent);
data.device_type = ua.device.type || 'desktop';
data.browser = ua.browser.name;
data.os = ua.os.name;
}
if (this.options.trackLocation) {
try {
const locationData = await this.fetchLocationData();
Object.assign(data, locationData);
} catch (error) {
console.warn('Failed to fetch location data:', error);
}
}
return data;
}
parseUserAgent(userAgent) {
// 简单解析,如果需要更精确的解析可以引入UAParser.js
const ua = userAgent.toLowerCase();
return {
browser: {
name: ua.includes('chrome') ? 'Chrome' :
ua.includes('firefox') ? 'Firefox' :
ua.includes('safari') ? 'Safari' :
ua.includes('edge') ? 'Edge' :
ua.includes('opera') ? 'Opera' : 'Unknown'
},
os: {
name: ua.includes('windows') ? 'Windows' :
ua.includes('mac os') ? 'Mac OS' :
ua.includes('linux') ? 'Linux' :
ua.includes('android') ? 'Android' :
ua.includes('ios') ? 'iOS' : 'Unknown'
},
device: {
type: ua.includes('mobile') ? 'mobile' :
ua.includes('tablet') ? 'tablet' : 'desktop'
}
};
}
async fetchLocationData() {
try {
const response = await fetch('https://ipapi.co/json/');
if (!response.ok) throw new Error('IP API request failed');
const ipData = await response.json();
return {
ip_address: ipData.ip,
country: ipData.country_name,
region: ipData.region,
city: ipData.city,
latitude: ipData.latitude,
longitude: ipData.longitude
};
} catch (error) {
console.warn('Location API error:', error);
return {};
}
}
async sendVisitorData(data) {
try {
const response = await fetch(`${this.supabaseUrl}/rest/v1/visitor_stats`, {
method: 'POST',
headers: {
'apikey': this.supabaseKey,
'Authorization': `Bearer ${this.supabaseKey}`,
'Content-Type': 'application/json',
'Prefer': 'return=minimal'
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
} catch (error) {
console.error('Error sending visitor data:', error);
throw error;
}
}
}
// 创建默认实例并自动收集数据(如果配置了自动跟踪)
if (typeof window !== 'undefined' && window.VisitorTrackerAutoInit !== false) {
const defaultTracker = new VisitorTracker(
'https://dshmbsawwrbuycnivcjs.supabase.co',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRzaG1ic2F3d3JidXljbml2Y2pzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTM5Mjg2OTAsImV4cCI6MjA2OTUwNDY5MH0.fwRJD-WuST7mCbJf9h2i2Xk0z6mtCMCeV--JGUecC6A',
{
trackLocation: true,
trackDevice: true,
trackReferrer: true
}
);
document.addEventListener('DOMContentLoaded', () => {
defaultTracker.collectAndSend();
});
}
// 导出模块
if (typeof module !== 'undefined' && module.exports) {
module.exports = VisitorTracker;
} else if (typeof define === 'function' && define.amd) {
define([], () => VisitorTracker);
} else {
window.VisitorTracker = VisitorTracker;
}