How to get page views on JavaScript?
I want to get and display how many times a page is viewed, just like Stack Overflow.
How to do it by JavaScript? Thx!
How to get page views on JavaScript?
I want to get and display how many times a page is viewed, just like Stack Overflow.
How to do it by JavaScript? Thx!
- 3 If you tried anything for yourself, post your code in your question. If you haven't tried anything for yourself, hire a programmer to do it. – Koby Douek Commented Aug 6, 2017 at 12:39
- That's not possible with client-side JavaScript. – PeterMader Commented Aug 6, 2017 at 12:39
- Possible duplicate of Is it possible to use JavaScript to track how many page views in past 24 hours? – A l w a y s S u n n y Commented Aug 6, 2017 at 12:46
5 Answers
Reset to default 3This can be done in javascript. You've to use browsers local storage to store the page view count to use it. You can use either window.localStorage or window.sessionStorage.
sessionStorage
will work like php session and will only be available through one browsing session, if you close the browser then sessionStorage data will be removed by browser. But, localStorage
will not be removed by browser until user manually delete browser data.
I'm gonna show you two implementations:
Using localStorage: you can store a variable into localStorage which can be used to count the page view. :
var myStorage = window.localStorage, pageCount;
window.addEventListener('load', function(){
if(!myStorage.getItem("pageCount")){
myStorage.setItem('pageCount', 1);
} else {
pageCount = myStorage.getItem("pageCount");
pageCount = pageCount + 1;
myStorage.setItem('pageCount', pageCount );
}
console.log('page view count', myStorage.getItem("pageCount"));
});
Or using window.sessionStorage :
var mySession = window.sessionStorage, pageCount;
window.addEventListener('load', function(){
if(!mySession.getItem("pageCount")){
mySession.setItem('pageCount', 1);
} else {
pageCount = mySession.getItem("pageCount");
pageCount = pageCount + 1;
mySession.setItem('pageCount', pageCount );
}
console.log('page view count of current browsing session', mySession.getItem("pageCount"));
});
If you want to track unique visitors to your site, you can use cookies to store a unique identifier for each visitor. Here's how you can modify the code to achieve this:
document.addEventListener('DOMContentLoaded', function() {
// Check if unique visitor ID exists in cookies
let uniqueVisitorId = getCookie('uniqueVisitorId');
if (!uniqueVisitorId) {
// If unique visitor ID does not exist, generate a new one
uniqueVisitorId = generateUniqueId();
// Set the unique visitor ID in cookies with expiry date
setCookie('uniqueVisitorId', uniqueVisitorId, 365); // Cookie expires in 365 days
}
// Check if the unique visitor ID is counted already
let isCounted = localStorage.getItem(uniqueVisitorId);
if (!isCounted) {
// If the unique visitor ID is not counted, increment the counter
let uniqueVisitors = parseInt(document.getElementById('uniqueVisitors').textContent);
uniqueVisitors++;
document.getElementById('uniqueVisitors').textContent = uniqueVisitors;
// Mark this unique visitor as counted
localStorage.setItem(uniqueVisitorId, 'true');
}
});
// Function to generate a unique ID
function generateUniqueId() {
return 'visitor_' + Math.random().toString(36).substr(2, 9);
}
// Function to set a cookie
function setCookie(name, value, days) {
let expires = '';
if (days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toUTCString();
}
document.cookie = name + '=' + (value || '') + expires + '; path=/';
}
// Function to get a cookie
function getCookie(name) {
let nameEQ = name + '=';
let cookies = document.cookie.split(';');
for(let i = 0; i < cookies.length; i++) {
let cookie = cookies[i];
while (cookie.charAt(0) == ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) == 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Views Counter</title>
</head>
<body>
<h1>Wele to My Site</h1>
<p>This site has been visited by <span id="uniqueVisitors">0</span> unique visitors.</p>
<script src="script.js"></script>
</body>
</html>
In this code:
- Generate a unique visitor ID for each visitor using a bination of a fixed prefix ('visitor_') and a random string.
- Store this unique visitor ID in a cookie with an expiry date of 365 days.
- Check if the unique visitor ID has already been counted by checking the local storage. If not, we increment the unique visitor count and mark this visitor as counted in local storage.
Using client-side JavaScript will not get the job done.
However, if you still want to use JavaScript then you should take a look at Node.js. Ideally, you would want to record the number of unique sessions, although, you can still record a page refresh as a page view.
This can be done with the following piece of code provided that you know how Node.js works:
var http = require('http'); // Require HTTP module
var pageViewCount = 0; // Declare and initialise the page view count
var server = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' }); // Headers
pageViewCount++; // Increase the page view count for every successful page load request
console.log('There are currently ' + pageViewCount + ' views'); // Output in console the amount of total page views
res.end();
});
server.listen(8000);
console.log('Server is currently running');
You can find more information regarding Node.js here: https://nodejs/en/docs/
Keep in mind that this answer requires some knowledge of Node.js but confirms that server-side JavaScript can be used to provide a solution to this particular problem.
With nodejs (serverside javascript) and express ( a library) you could do the following:
var counter = 0;
var app = require("express");
app.get("/",function(req,res){
counter++;
res.render("main.ejs",{counter});
});
app.listen(80);
main.ejs should look like this:
The page was visited <%= counter %> times...
You might want to store that in Database.