1

I try to delete a cookie via Javascript but it seems it remains having its value.

function setCookie(cname, cvalue, exdays=1) {
   let 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(name) {
   let cookieValue = null;
   if (document.cookie && document.cookie != '') {
   >   let cookies = document.cookie.split(';');
   >   for (let i = 0; i < cookies.length; i++) {
   >   >   let cookie = jQuery.trim(cookies[i]);
   >   >   // Does this cookie string begin with the name we want?
   >   >   if (cookie.substring(0, name.length + 1) == (name + '=')) {
   >   >   >   cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
   >   >   >   break;
   >   >   }
   >   }
   }
   return cookieValue;
}

function deleteCookie(name) {
   //document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
   document.cookie = `${name}= ; expires = Thu, 01 Jan 1970 00:00:00 GMT`;
   console.log(document.cookie);
}

Do you something wrong with the delete function code? Maybe the spaces?

setCookie('locinfo', '1292|MAG Trolley-05||1150|BOX2016-S1');
deleteCookie('locinfo');

Thanks in advance

Ruben
  • 1,065
  • 5
  • 18
  • 44

1 Answers1

0

By creating the cookie, I was adding the path

document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";

So, when deleting I also need to add the path and it works.

function deleteCookie(name) {
   document.cookie = `${name}= ; expires = Thu, 01 Jan 1970 00:00:00 GMT`;path=/;
}
Ruben
  • 1,065
  • 5
  • 18
  • 44