Track Number of User Visits With JavaScript Local Storage

And show personalized content on browser based on data

With the help of the browser’s LocalStorage, we can keep track of the number of visits of a user on the website or a particular webpage. Based on this data, customized alerts, messages or information can be shown to the user.

Below is the demo of one such use case. Notice the visit count and welcome message change as you reload the page. Clear cache and reload to start over.

Demo

This is your visit number to this webpage.

Welcome back! Thank you for returning.


Demo Code

<p>This is your visit <strong id="visit"></strong> to this webpage. </p>
<div id="special-message">Welcome back! Thank you for returning.</div>

<button onclick="reload()">Reload</button> <br>

<button onclick="clearCacheAndReload()">Clear Cache & Reload</button>

<script>
  var numberOfVisits = localStorage.getItem("numberOfVisits");

  if (!numberOfVisits) {
    numberOfVisits = 0;
  }
  numberOfVisits = +numberOfVisits + 1; 

  localStorage.setItem("numberOfVisits", numberOfVisits);
  document.getElementById("visit").innerHTML = numberOfVisits;

  if (numberOfVisits < 2) {
    document.getElementById("special-message").innerHTML = 
    "Thanks for visiting!";
  }

  function clearCacheAndReload() {
    localStorage.removeItem("numberOfVisits");
    location.reload();
  }

  function reload() {    
    location.reload();
  }
</script>



See also

When you purchase through links on techighness.com, I may earn an affiliate commission.