Here's a simple JavaScript script that uses localStorage to store and manage visitor count, unique daily visitors, and unique monthly visitors. This script assumes that the visitor's browser supports localStorage and that the visitor has not disabled it.
javascript
// Check if localStorage is supported
if (typeof(Storage) !== "undefined") {
// Generate a unique identifier for the visitor
function generateUUID() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c == "x" ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// Get the current date
function getCurrentDate() {
const date = new Date();
return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}
// Get the current month
function getCurrentMonth() {
const date = new Date();
return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}`;
}
// Initialize the visitor data
function initializeVisitorData() {
const visitorData = {
totalVisits: 0,
dailyVisitors: {},
monthlyVisitors: {}
};
// Load the data from localStorage if it exists
if (localStorage.getItem("visitorData")) {
visitorData.totalVisits = parseInt(localStorage.getItem("visitorData").totalVisits);
visitorData.dailyVisitors = JSON.parse(localStorage.getItem("visitorData").dailyVisitors);
visitorData.monthlyVisitors = JSON.parse(localStorage.getItem("visitorData").monthlyVisitors);
}
return visitorData;
}
// Update the visitor data
function updateVisitorData(visitorData) {
const currentDate = getCurrentDate();
const currentMonth = getCurrentMonth();
const visitorID = generateUUID();
// Update total visits
visitorData.totalVisits++;
// Update daily visitors
if (!visitorData.dailyVisitors[currentDate]) {
visitorData.dailyVisitors[currentDate] = [];
}
if (!visitorData.dailyVisitors[currentDate].includes(visitorID)) {
visitorData.dailyVisitors[currentDate].push(visitorID);
}
// Update monthly visitors
if (!visitorData.monthlyVisitors[currentMonth]) {
visitorData.monthlyVisitors[currentMonth] = [];
}
if (!visitorData.monthlyVisitors[currentMonth].includes(visitorID)) {
visitorData.monthlyVisitors[currentMonth].push(visitorID);
}
// Save the data to localStorage
localStorage.setItem("visitorData", JSON.stringify(visitorData));
}
// Initialize and update the visitor data
const visitorData = initializeVisitorData();
updateVisitorData(visitorData);
} else {
console.log("Sorry, your browser does not support localStorage.");
}
This script generates a unique identifier for each visitor and stores it in the dailyVisitors and monthlyVisitors objects. The totalVisits property keeps track of the total number of visits. The script also checks if the visitor has visited the site on the current day and month, and only increments the count if they have not.