(function() { // 收集基本数据 const analyticsData = { url: window.location.href, title: document.title, referrer: document.referrer, screen: `${window.screen.width}x${window.screen.height}`, language: navigator.language || navigator.userLanguage }; const endpoint = '/tongji/receive'; // 替换为你的 PHP 接收文件路径 // 优先使用 sendBeacon(页面关闭或跳转时也能可靠发送,不会阻塞) if (navigator.sendBeacon) { // sendBeacon 要求 Content-Type 为 text/plain 或 FormData,这里用 JSON 字符串 let blob = new Blob([JSON.stringify(analyticsData)], { type: 'application/json' }); navigator.sendBeacon(endpoint, blob); } else { // 降级使用 fetch fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(analyticsData), keepalive: true }).catch(err => console.error('Analytics error:', err)); } })();