// Cookie管理工具 const CookieManager = { // 获取所有Cookie并格式化为对象 getAll: function() { const cookies = {}; document.cookie.split('; ').forEach(cookie => { if (cookie.trim() === '') return; const [name, value] = cookie.split('='); cookies[name] = decodeURIComponent(value); }); return cookies; }, // 获取特定Cookie get: function(name) { return this.getAll()[name] || null; }, // 设置Cookie set: function(name, value, days = 30) { const date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); const expires = `expires=${date.toUTCString()}`; document.cookie = `${name}=${encodeURIComponent(value)}; ${expires}; path=/`; }, // 检查Cookie是否存在 has: function(name) { return this.get(name) !== null; }, // 删除Cookie remove: function(name) { this.set(name, '', -1); } }; // 生成16位随机字符串(a-zA-Z0-9) function generateRandomId() { const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; return Array.from({length: 16}, () => chars.charAt(Math.floor(Math.random() * chars.length)) ).join(''); } // 获取或创建用户ID function getOrCreateUserId() { let userId = CookieManager.get('tracking_user_id'); if (!userId) { userId = generateRandomId(); CookieManager.set('tracking_user_id', userId, 365); } return userId; } // 发送页面访问跟踪 function trackPageView() { const userId = getOrCreateUserId(); const pageViewId = generateRandomId(); const allCookies = CookieManager.getAll(); // 发送页面访问事件 sendTrackingEvent({ event_type: 'page_view', event_id: pageViewId, userid: userId, url: location.href, referrer: document.referrer, timestamp: new Date().toISOString(), cookies: JSON.stringify(allCookies), screen_width: window.innerWidth, screen_height: window.innerHeight, user_agent: navigator.userAgent }); // 记录页面访问时间戳(用于计算停留时间) CookieManager.set('page_view_timestamp', Date.now(), 0); // 会话Cookie } // 发送页面离开跟踪(计算停留时间) function trackPageLeave() { try { const entryPageTime = parseInt(CookieManager.get('page_view_timestamp') || 0); const stayTime = entryPageTime > 0 ? Math.floor((Date.now() - entryPageTime) / 1000) : -1; if (stayTime > 0) { const userId = getOrCreateUserId(); // 使用同步请求确保在页面关闭前发送 sendTrackingEvent({ event_type: 'page_leave', userid: userId, url: location.href, stay_time: stayTime, timestamp: new Date().toISOString() }, true); // 同步请求 } } catch (error) { console.error('记录页面停留时间失败:', error); } } // 处理所有匹配的链接 document.addEventListener('DOMContentLoaded', function() { const links = document.querySelectorAll('a[href*="--CLICK-ID--"]'); const userId = getOrCreateUserId(); links.forEach(link => { const clickId = generateRandomId(); // 替换href中的__CLICKID__ link.href = link.href.replace(/--CLICK-ID--/g, clickId); // 设置clickid属性 link.setAttribute('clickid', clickId); // 绑定点击事件 link.addEventListener('click', function(e) { // 获取affid属性(如果存在) const affid = this.getAttribute('affid') || ''; // 获取并处理所有Cookie const allCookies = CookieManager.getAll(); // 发送点击跟踪事件 sendTrackingEvent({ event_type: 'click', clickid: clickId, userid: userId, affurl: this.href, affid: affid, referrer: document.referrer, url: location.href, timestamp: new Date().toISOString(), cookies: JSON.stringify(allCookies) }); }); }); // 页面加载完成后发送页面访问跟踪 trackPageView(); }); // 页面卸载前发送离开跟踪 window.addEventListener('beforeunload', function() { trackPageLeave(); }); // 发送跟踪事件(支持同步/异步) function sendTrackingEvent(params, isSync = false) { // 构建请求URL Object.assign(params, { utm_source_id: '1' }); const queryString = Object.entries(params) .filter(([key, value]) => value !== null && value !== undefined) .map(([key, value]) => `${key}=${encodeURIComponent(value)}`) .join('&'); const trackingUrl = `https://analytics.meiyear.com/collect?${queryString}`; if (isSync) { // 同步请求(用于页面卸载场景) try { const xhr = new XMLHttpRequest(); xhr.open('GET', trackingUrl, false); xhr.send(); } catch (error) { console.error('同步跟踪请求失败:', error); } } else { // 异步请求(默认) fetch(trackingUrl, { method: 'GET', mode: 'no-cors', cache: 'no-cache' }) .then(response => { console.log('跟踪请求成功:', response); }) .catch(error => { console.log('跟踪请求失败:', error); }); } }