Last Visit Cookie
Enhance visitor retention with personalization. This script uses JavaScript cookies to remember a user's name and track their visit frequency, displaying a friendly "Welcome Back" message with their last login date.
Persistence Demo
Hello, Visitor!
Loading visit history...
Copy the Script
<script>
/* Configuration: How many days to store the cookie */
var expDays = 365;
function setCookie(name, value) {
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + exp.toUTCString() + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length));
}
return null;
}
// Main Logic
var visitName = getCookie("visitorName");
var lastVisit = getCookie("lastVisitTime");
var currentVisit = new Date().toLocaleString();
if (visitName == null) {
// First time visitor
visitName = prompt("Welcome! Please enter your name:", "Guest");
if(visitName == null || visitName == "") visitName = "Guest";
setCookie("visitorName", visitName);
setCookie("lastVisitTime", currentVisit);
document.write("Hello " + visitName + "! This is your first visit.");
} else {
// Returning visitor
document.write("Welcome back, " + visitName + "!<br>");
if (lastVisit) {
document.write("Your last visit was on: " + lastVisit);
}
// Update the time for next visit
setCookie("lastVisitTime", currentVisit);
}
</script>
Frequently Asked Questions
The script includes an expiration parameter. By default, it is set to 365 days, but you can adjust the 'expDays' variable in the code.
No. If a user has disabled cookies in their browser settings, this script will not be able to save or retrieve the visit data.
Since this script stores personal data (potentially a name), you should ask for user consent via a cookie banner before running the script to be fully compliant.