Below is a simple JavaScript script that utilizes localStorage to track and update visitor counts, including unique daily and monthly visitors. This script assumes you want to count visitors based on their device/browser (since that's the scope of localStorage). Note that this approach has limitations, such as not accounting for visitors who clear their browser storage or access your site from different devices/browsers.
javascript
// Function to get the current date in YYYY-MM-DD format for daily tracking
// and YYYY-MM for monthly tracking
function getCurrentDate(type) {
const date = new Date();
let dateString;
if (type === 'daily') {
dateString = date.toISOString().split('T')[0]; // YYYY-MM-DD
} else if (type === 'monthly') {
dateString = date.toISOString().split('T')[0].slice(0, 7); // YYYY-MM
}
return dateString;
}
// Function to initialize storage if it doesn't exist
function initializeStorage() {
if (!localStorage.getItem('visitorData')) {
localStorage.setItem('visitorData', JSON.stringify({
totalVisitors: 0,
uniqueDailyVisitors: {},
uniqueMonthlyVisitors: {}
}));
}
}
// Function to generate a unique visitor ID using UUID
function getVisitorId() {
const storedId = localStorage.getItem('visitorUUID');
if (!storedId) {
// Generate a UUID and store it in localStorage
const uuid = crypto.randomUUID();
localStorage.setItem('visitorUUID', uuid);
return uuid;
}
return storedId;
}
// Function to update visitor counts
function updateVisitorCount() {
try {
// Initialize storage if it doesn't exist
initializeStorage();
const storedData = JSON.parse(localStorage.getItem('visitorData'));
const currentDay = getCurrentDate('daily');
const currentMonth = getCurrentDate('monthly');
const visitorId = getVisitorId();
// Update Counts
storedData.totalVisitors++;
// Track unique daily visitors
if (!storedData.uniqueDailyVisitors[currentDay]) {
storedData.uniqueDailyVisitors[currentDay] = new Set();
}
storedData.uniqueDailyVisitors[currentDay].add(visitorId);
// Track unique monthly visitors
if (!storedData.uniqueMonthlyVisitors[currentMonth]) {
storedData.uniqueMonthlyVisitors[currentMonth] = new Set();
}
storedData.uniqueMonthlyVisitors[currentMonth].add(visitorId);
// Save updated data
localStorage.setItem('visitorData', JSON.stringify(storedData));
// Optionally, display the updated counts
displayVisitorCounts(storedData);
} catch (error) {
console.error("Error updating visitor count:", error);
// Handle storage limits or other errors gracefully
if (error.name === 'QuotaExceededError') {
console.log("Storage limit exceeded. Clearing old data...");
clearOldVisitorData();
}
}
}
// Function to display the visitor counts (Optional)
function displayVisitorCounts(data) {
const dailyVisitors = Object.keys(data.uniqueDailyVisitors).reduce((acc, day) => acc + data.uniqueDailyVisitors[day].size, 0);
const monthlyVisitors = Object.keys(data.uniqueMonthlyVisitors).reduce((acc, month) => acc + data.uniqueMonthlyVisitors[month].size, 0);
console.log(`Total Visitors: ${data.totalVisitors}`);
console.log(`Unique Daily Visitors (across all tracked days): ${dailyVisitors}`);
console.log(`Unique Monthly Visitors (across all tracked months): ${monthlyVisitors}`);
// You can also update HTML elements here to display the counts on your page
}
// Function to clear old visitor data in case of storage limit issues
function clearOldVisitorData() {
const storedData = JSON.parse(localStorage.getItem('visitorData'));
// Remove data older than 30 days
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
Object.keys(storedData.uniqueDailyVisitors).forEach(dateString => {
const date = new Date(dateString);
if (date < thirtyDaysAgo) {
delete storedData.uniqueDailyVisitors[dateString];
}
});
localStorage.setItem('visitorData', JSON.stringify(storedData));
}
// Call the function to update the visitor count on page load
document.addEventListener('DOMContentLoaded', updateVisitorCount);
Important Considerations:
UUID Generation: The script includes a basic implementation for generating a unique visitor ID using crypto.randomUUID(). Ensure your environment supports this method. For older browsers, you might need a polyfill.
Privacy and Compliance: Storing visitor information, even if just a UUID, might have privacy implications. Ensure you comply with regulations like GDPR or CCPA, if applicable. Consider adding a privacy policy that explains what data is collected and how it is used.
Accuracy and Limitations: As mentioned, this approach doesn't account for visitors across different devices or browsers, nor does it handle cases where visitors clear their storage. For more accurate tracking, consider using server-side logging or third-party analytics tools.
Server-Side Alternative: For more accurate and robust visitor tracking, consider implementing a server-side solution that logs visitor information upon each request, utilizing IP addresses, user agents, and cookies/UUIDs stored in a database. This approach can also help mitigate storage limit issues.
Storage Limits: The updated script includes error handling for storage limits (QuotaExceededError). If the limit is exceeded, it clears old data (older than 30 days) to ensure functionality.
Alternative Tracking Methods:
Google Analytics: A popular choice for tracking website visitors, offering detailed insights into user behavior and demographics.
Server-Side Logging: Storing visitor data on your server using IP addresses, user agents, and cookies provides more accurate tracking across devices.
Fingerprinting Techniques: Collecting information like browser type, screen resolution, and device characteristics can help identify unique visitors without storing personal data.