Public Access
1
0

new: view counter

This commit is contained in:
giteaadmin
2025-08-22 23:28:53 -04:00
parent af4501e527
commit ecdac48379
7 changed files with 132 additions and 8 deletions

38
src/js/view-counter.js Normal file
View File

@@ -0,0 +1,38 @@
document.addEventListener('DOMContentLoaded', () => {
const viewCountElement = document.querySelector('[data-view-count]');
if (viewCountElement) {
const slug = viewCountElement.dataset.slug;
const serverUrl = 'http://localhost:3000'; // IMPORTANT: Replace with your server's IP/domain
// Function to fetch and display the view count
const getViews = async () => {
try {
const response = await fetch(`${serverUrl}/api/views/${slug}`);
if (!response.ok) throw new Error('Failed to fetch views');
const data = await response.json();
viewCountElement.textContent = `${data.count} views`;
} catch (error) {
console.error('Error getting views:', error);
viewCountElement.textContent = 'Could not load views';
}
};
// Function to increment the view count
const incrementView = async () => {
try {
// Use a flag in localStorage to prevent incrementing on every refresh
const viewed = localStorage.getItem(`viewed-${slug}`);
if (!viewed) {
await fetch(`${serverUrl}/api/views/${slug}`, { method: 'POST' });
localStorage.setItem(`viewed-${slug}`, 'true');
}
} catch (error) {
console.error('Error incrementing view:', error);
}
};
// Run the functions
incrementView().then(getViews);
}
});