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"));
});

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

```