When using localStorage, the counts are indeed browser-specific because localStorage only persists data locally within the same browser. If you need the page view count to aggregate across all visitors and browsers, you'll need to use a server-side solution.
Here is a simple example using a backend server with Node.js and Express to track page views. Note that deploying a server generally requires some setup and hosting, but the following example demonstrates the basic concepts.
1. Setup a Node.js Server
Step 1: Initialize a Node.js Project
First, you need to ensure Node.js and npm (Node Package Manager) are installed on your machine.
npm init -y
This will create a package.json file.
Step 2: Install Express
Install the Express framework to handle HTTP requests.
npm install express
Step 3: Create a Simple Server
Create a file named server.js in the root of your project directory.
server.js
const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const PORT = 3000;
let pageViews = 0;
// Read existing count from file (if it exists)
const filePath = path.join(__dirname, 'views.json');
if (fs.existsSync(filePath)) {
const data = fs.readFileSync(filePath, 'utf8');
pageViews = JSON.parse(data).views || 0;
}
// Endpoint to get and increment page views
app.get('/api/page-views', (req, res) => {
pageViews++;
fs.writeFileSync(filePath, JSON.stringify({ views: pageViews }), 'utf8');
res.json({ views: pageViews });
});
// Serve static files including index.html
app.use(express.static('public'));
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Project Structure
Your directory should look like this:
my-project/
│
├── node_modules/
├── public/
│ ├── assets/
│ │ ├── images/
│ │ │ └── sslogo.png
│ ├── index.html
│ └── main.js
├── views.json (will be created by server.js)
├── package.json
└── server.js
2. Update the HTML and JavaScript
Move your existing HTML and JavaScript files into the public directory:
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Title</title>
<!-- Include Bootstrap Icons CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.6.1/font/bootstrap-icons.min.css">
<style>
.page-wrapper{
/* Your existing styles */
}
.upper {
/* Your existing styles */
}
.pageViews {
font-size: 16px;
color: #333;
display: flex;
align-items: center;
}
.pageViews i {
margin-right: 5px;
}
.profile-pic-img {
/* Your existing styles */
}
.firmname {
/* Your existing styles */
}
.firmname-underline {
/* Your existing styles */
}
.name {
/* Your existing styles */
}
</style>
</head>
<body>
<div class="page-wrapper" id="home-section">
<div class="upper">
<div class="pageViews"><i class="bi bi-eye-fill"></i> Views: <b id="viewCount">0</b></div>
<img src="assets/images/sslogo.png" class="profile-pic-img false">
<div class="firmname">SOUND SOLUTIONS</div>
<div class="firmname-underline"></div>
<div class="name">Mr. <!-- --> <!-- --> FATEMA <!-- --> <!-- --> SHAIKH <!-- --> <span
style="margin-top:5px;display:block"><i style="font-size:12px">( <!-- -->DIRECTOR CORPORATE SALES <!-- -->)</i></span></div>
</div>
</div>
<!-- Link to external JavaScript file -->
<script src="main.js"></script>
</body>
</html>
public/main.js
document.addEventListener("DOMContentLoaded", function() {
// Fetch the current count from the server
fetch('/api/page-views')
.then(response => response.json())
.then(data => {
// Update the page with the new count
document.getElementById('viewCount').textContent = data.views;
})
.catch(err => console.error('Error fetching page views:', err));
});
3. Start the Server
Run the following command in your project's root directory to start the server:
node server.js
Open your browser and navigate to http://localhost:3000. This will display your index.html file, and the page views should be aggregated across all visitors who access this URL.
Explanation
- Server Setup: The Node.js server uses Express to handle a simple API endpoint (
/api/page-views) that increments the page view count and serves static files.
- File Persistence: The server stores the page view count in a
views.json file so that the count persists even if the server restarts.
- JavaScript Fetch: The client-side JavaScript fetches the current page view count from the server via the
/api/page-views endpoint and updates the DOM.
This setup allows you to maintain a page view count that aggregates across multiple browsers and visitors.