Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

A Function to Check a Cookie

Finally, we define a function that checks if a cookie is set.

If the cookie exists, it will display a greeting message.

If the cookie is not set, it will show a prompt asking for the user’s name and then store the username in a cookie for 365 days by calling the setCookie function.

Example

function checkCookie() {
  let username = getCookie(“username”);
  if (username != “”) {
   alert(“Welcome again “ + username);
  } else {
    username = prompt(“Please enter your name:”“”);
    if (username != “” && username != null) {
      setCookie(“username”, username, 365);
    }
  }
}

All Together Now

Example

function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  let expires = “expires=”+d.toUTCString();
  document.cookie = cname + “=” + cvalue + “;” + expires + “;path=/”;
}

function getCookie(cname) {
  let name = cname + “=”;
  let ca = document.cookie.split(‘;’);
  for(let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ‘ ‘) {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return “”;
}

function checkCookie() {
  let user = getCookie(“username”);
  if (user != “”{
    alert(“Welcome again “ + user);
  } else {
    user = prompt(“Please enter your name:”“”);
    if (user != “” && user != null) {
      setCookie(“username”, user, 365);
    }
  }
}

The example above calls the checkCookie() function when the page is loaded.