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
- SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your key and signing method.
- Yup Date Format Validation With Moment JS
- Yup Number Validation: Allow Empty String
- Exactly Same Query Behaving Differently in Mongo Client and Mongoose
- JavaScript Unit Testing JSON Schema Validation
- Reduce JS Size With Constant Strings
- JavaScript SDK