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
- Reduce JS Size With Constant Strings
- JavaScript SDK
- JavaScript: Find if the String Has a Particular Case
- Replace All Keys of Deeply Nested Objects or Array of Objects in JavaScript
- Restrict Content for Users of Specific Countries With JavaScript Only
- React JS Render Form With Dynamic Conditional Fields
- React JS Render Form With Dynamic Data From Backend API