Files
huicai/src/utils/tracking.js
2026-08-04 13:21:17 +08:00

48 lines
1.2 KiB
JavaScript

import axios from 'axios'
const service = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
timeout: 15000,
})
const VISITOR_KEY = 'huicai_visitor_key'
const VISIT_MARK = 'huicai_visit_mark'
function randomKey() {
return `${Date.now()}_${Math.random().toString(36).slice(2, 12)}`
}
export function getVisitorKey() {
let key = localStorage.getItem(VISITOR_KEY)
if (!key) {
key = randomKey()
localStorage.setItem(VISITOR_KEY, key)
}
return key
}
function todayMark(path) {
return `${new Date().toISOString().slice(0, 10)}:${path}`
}
export function trackVisit(route) {
const path = route.fullPath || route.path || '/'
const mark = todayMark(path)
if (localStorage.getItem(VISIT_MARK) === mark) return
localStorage.setItem(VISIT_MARK, mark)
service.post('/site/visit', {
visitor_key: getVisitorKey(),
path,
page_title: route.meta?.title || document.title || path,
})
}
export function trackPageView(route) {
service.post('/site/page-view', {
visitor_key: getVisitorKey(),
path: route.fullPath || route.path || '/',
page_title: route.meta?.title || document.title || route.path || '/',
referrer: document.referrer || '',
})
}