Setting and deleting cookies

Posted under » JavaScript on 28 Jul 2021

It is very simple to create a cookie using javascript instead of php or python.

<script type="text/javascript">
document.cookie = "username=Brad Pitt"; 
</script>

To read or retrieve the username is tricky.

function getCookie(cname) {
  let name = cname + "=";
 let decodedCookie = decodeURIComponent(document.cookie);
   let ca = decodedCookie.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 "";
 }

let userid = getCookie("username");
alert("Welcome again " + userid);

However, to delete you need to specify the path and set an expiry date.

<script type="text/javascript">
document.cookie = "username=; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/inner";
</script>

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS