Copyright © 2022-2025 All Rights Reserved 版权所有 牙聘网
地址: EMAIL:zslwzxg@qq.com// 页面访问统计函数 function trackPageView() { // 从本地存储获取当前访问数据 const storedData = localStorage.getItem('websiteStats'); const stats = storedData ? JSON.parse(storedData) : { totalVisits: 0, todayVisits: 0, activeUsers: 0, avgTime: 0, lastVisitDate: '', visitsByDay: [], sources: [], pages: [] }; // 获取当前日期 const today = new Date().toISOString().split('T')[0]; // 初始化今天的访问数据 if (!stats.lastVisitDate || stats.lastVisitDate !== today) { stats.lastVisitDate = today; stats.todayVisits = 0; // 记录每天的访问量 stats.visitsByDay.push({ date: today, visits: 0 }); // 只保留最近30天的数据 if (stats.visitsByDay.length > 30) { stats.visitsByDay.shift(); } } // 更新访问数据 stats.totalVisits++; stats.todayVisits++; // 更新今天的访问量 const todayIndex = stats.visitsByDay.findIndex(day => day.date === today); if (todayIndex !== -1) { stats.visitsByDay[todayIndex].visits++; } // 记录页面访问 const currentPath = window.location.pathname; const pageIndex = stats.pages.findIndex(page => page.path === currentPath); if (pageIndex !== -1) { stats.pages[pageIndex].visits++; // 简单计算平均停留时间(实际应用中应该使用更复杂的计算方法) stats.pages[pageIndex].totalTime += Math.floor(Math.random() * 60) + 10; stats.pages[pageIndex].avgTime = Math.floor(stats.pages[pageIndex].totalTime / stats.pages[pageIndex].visits); } else { stats.pages.push({ path: currentPath, title: document.title, visits: 1, totalTime: Math.floor(Math.random() * 60) + 10, avgTime: Math.floor(Math.random() * 60) + 10, bounceRate: Math.floor(Math.random() * 30) + 20 }); } // 计算来源(简化版) const referrer = document.referrer; let sourceType = 'direct'; if (referrer.includes('google') || referrer.includes('baidu') || referrer.includes('bing')) { sourceType = 'search'; } else if (referrer.includes('weibo') || referrer.includes('wechat') || referrer.includes('twitter') || referrer.includes('facebook')) { sourceType = 'social'; } else if (referrer && referrer !== '') { sourceType = 'external'; } const sourceIndex = stats.sources.findIndex(source => source.type === sourceType); if (sourceIndex !== -1) { stats.sources[sourceIndex].count++; } else { stats.sources.push({ type: sourceType, count: 1 }); } // 模拟活跃用户数(实际应用中应该使用会话管理) stats.activeUsers = Math.floor(Math.random() * 50) + 50; // 模拟平均停留时间 stats.avgTime = Math.floor(Math.random() * 120) + 30; // 计算增长率(与前一天相比) if (stats.visitsByDay.length >= 2) { const todayVisits = stats.visitsByDay[stats.visitsByDay.length - 1].visits; const yesterdayVisits = stats.visitsByDay[stats.visitsByDay.length - 2].visits; if (yesterdayVisits > 0) { stats.totalVisitsGrowth = Math.round(((todayVisits - yesterdayVisits) / yesterdayVisits) * 100); } } // 保存数据到本地存储 localStorage.setItem('websiteStats', JSON.stringify(stats)); } // 页面加载完成后执行 document.addEventListener('DOMContentLoaded', () => { // 初始化页面跟踪 trackPageView(); });
Powered by PHPYun.