DEV Community

Michael Burrows
Michael Burrows

Posted on • Updated on • Originally published at w3collective.com

Display a message to returning visitors using a JavaScript cookie

Cookies are small strings of data stored on your computer that can be accessed by a web browser.

By using cookies we can detect if a visitor has visited a website before from the same browser.

This can be useful for showing a customised message or directing visitors to a special promotion.

NOTE – Chrome doesn’t store cookies from pages loaded on the local file system (file://).

Let’s start by defining our cookie name and calling a function to check if the cookie already exists.

document.addEventListener("DOMContentLoaded", function () {
  const userCookieName = "returningVisitor";
  checkUserCookie(userCookieName);
});
Enter fullscreen mode Exit fullscreen mode

If the cookie exists then insert HTML with our message otherwise call a function to create the cookie.

function checkUserCookie(userCookieName) {
  const regEx = new RegExp(userCookieName, "g");
  const cookieExists = document.cookie.match(regEx);
  if (cookieExists != null) {
    document.body.insertAdjacentHTML(
      "beforeend",
      '<div id="welcome">Welcome back friend! Check out our latest thing <a href="#">HERE</a></div>'
    );
  } else {
    createUserCookie(userCookieName);
  }
}
Enter fullscreen mode Exit fullscreen mode

Lastly we create the cookie using document.cookie with our cookie name, value and an expiry date.

function createUserCookie(userCookieName) {
  const userCookieValue = "Yes";
  const userCookieDays = 7;
  let expiryDate = new Date();
  expiryDate.setDate(expiryDate.getDate() + userCookieDays);
  document.cookie = userCookieName + "=" + userCookieValue +"; expires=" + expiryDate.toGMTString() + "path=/";
}
Enter fullscreen mode Exit fullscreen mode

Now if you refresh the browser you should see the message which we can pretty up with some CSS.

#welcome {
  position: fixed;
  bottom: 0;
  width: 100%;
  padding: 10px 0;
  background: rgb(14, 108, 170);
  color: #fff;
  text-align: center;
}
#welcome a {
  color: #fff;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
yougotwill profile image
Will G

Nice post. Thanks!

Collapse
 
viper619 profile image
viper

Cool stuff