Question: 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!

Answer: 
This 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](https://developer.mozilla.org/en/docs/Web/API/Window/localStorage) or [window.sessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/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"));
});

```
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.org/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.