Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to delete cookie from javascript

I am on an external site, and I am trying to delete the cookie via javascript.

I did the following in the console:

function deleteAllCookies() {     var cookies = document.cookie.split(";");      for (var i = 0; i < cookies.length; i++) {         var cookie = cookies[i];         var eqPos = cookie.indexOf("=");         var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;         document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";     } }  deleteAllCookies() 

which is supposed to set the document cookie to expire in 1970

But after that, I call

document.cookie.split(";") 

The cookies are seemingly untouched. Any ideas why?

PS: code above is from stackoverflow Clearing all cookies with JavaScript

like image 606
meow Avatar asked Apr 16 '11 18:04

meow


People also ask

Can you delete cookies from JavaScript?

JavaScript can create, read, and delete cookies with the document.

Why can't I delete cookies?

Moreover, if you try to remove the Google services cookies, the browser will automatically re-create them, making it impossible to remove data stored on Google servers. Thankfully, you can fix it by logging out of the Google services and then clearing out the browser history.

Can we delete HttpOnly cookie in JavaScript?

In order to delete a cookie from JS, therefore, you need to ensure that you are addressing the correct cookie by both name and flag values, and that it doesn't have HTTPOnly flag set, and that you're on a page with a HTTPS certificate. If any of these are not true, you won't be able to edit/delete it.


Video Answer


2 Answers

Your cookie is most likely not being deleted because when you set the new value, it has to match the path and domain of the original cookie you're trying to delete.

In other words:

 document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=[something];" 

that "something" value needs to line up with whatever the existing cookies have set.

JS debuggers might not give you details on what the path and domain are, but it will become obvious which one you're not matching on if you look up the value of the existing cookie in your Chrome->settings or similar panel in Firefox/Safari/IE.

Let me know if that helps.

like image 164
Stan Lin Avatar answered Sep 21 '22 11:09

Stan Lin


I had the same issue. I discovered that the cookie was set under an empty subdomain, e.g. the cookie domain was ".domain.com", and my website was hosted at "sub.domain.com".

To fix I added the cookie domain to the set value

document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=.domain.com"; 

To see what domain the cookie is set to, in Chrome, open dev tools -> resources -> cookies and look at the domain fields.

like image 28
WearyMonkey Avatar answered Sep 22 '22 11:09

WearyMonkey