#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

Using a cookie to track returning website visitors

Last modified February 5th 2021 | GitHub Source Code [GitHub] | #js

Cookies are small strings of data stored on your computer that can be accessed by a web browser. Using cookies we can track returning website visitors (from the same browser). For the purposes of this tutorial we’ll be displaying a custom message for return visitors.

NOTE – Chrome doesn’t store cookies from pages loaded on the local file system (file://). You’ll need to test this code on a server or in another browser like Firefox or Safari.

Let’s get started by creating a new HTML file with the following markup:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
</html>Code language: HTML, XML (xml)

Now for the JavaScript, we need to declare a name for our cookie and then we can call the checkUserCookie function which will check if the returningVisitor cookie already exists:

document.addEventListener("DOMContentLoaded", function () {
  const userCookieName = "returningVisitor";
});Code language: JavaScript (javascript)

Next comes the checkUserCookie function, if the cookie does exist then we insert some HTML with a custom message otherwise we call a function to create the cookie:

function checkUserCookie(userCookieName) {
  const cookieExists = document.cookie.match(userCookieName);
  if (cookieExists != null) {
      '<div id="welcome">Welcome back friend! Check out our latest thing <a href="#">HERE</a></div>'
  } else {
}Code language: JavaScript (javascript)

Lastly the createUserCookie function which creates a new cookie using document.cookie. The cookie value is set to “Yes” but this could be anything as it’s not actually used in this instance, this would be used if you wanted to retrieve a stored value from the cookie. You can also define how long a cookie should last in this case the cookie will expire after 7 days:

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=/";
}Code language: PHP (php)

With the JavaScript complete let’s add some basic CSS for our message:

#welcome {
  position: fixed;
  bottom: 0;
  width: 100%;
  padding: 10px 0;
  background: rgb(14, 108, 170);
  color: #fff;
  text-align: center;
#welcome a {
  color: #fff;
}Code language: CSS (css)

If you view the HTML page in a browser you should see nothing but a blank page. On the first viewing the cookie doesn’t exist so the new cookie created. On refresh the cookie will be detected which then triggers the custom message.

Related Posts

#AD Shop Web Developer T-Shirts