0

I wrote a while ago a function for removing cookies using mootools. Which worked great. I'm now trying to get it to work in jQuery using the js-cookie libary. I've been trying to get this to work for about 4 hours now and I've now started to bang my head on the table :(

function deleteAllCookies() {
console.log('got to delete all cookies');
var cookies = document.cookie.split(";");
console.log("cookie length"+cookies.length);
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;
    Cookies.remove(name, null);
    console.log("name is "+name);
}

}

so it finds two cookies and gets the names correctly but it only deletes one of them (the first one). If I run it again it deletes the second one. Any ideas what I'm doing wrong. (I call the function from a onmousedown event for testing)

thanks

user1616338
  • 557
  • 1
  • 8
  • 24
  • Any reason not to just Google `jquery delete all cookies` and copy/paste one of the solutions given there? Or `javascript delete all cookies`. If you want to do this for learning purposes, this calls for basic debugging first - can you try to trace what goes wrong where? What does `cookies.length` return? Etc. – Pekka Feb 19 '17 at 21:12
  • I put in trace. cookies.length is 2 in length, I also put a console .log on the remove function to check it's being called. So I checked that I had the correct two cookie names and that the remove function was being called twice. As to the Google idea I have googled it and tried the code that's what got me to this code. – user1616338 Feb 19 '17 at 21:25

1 Answers1

0

Do the cookies have the same name but different attributes? The spec doesn't define a behavior for that so it's undefined behavior and each browser can implement their own. One should avoid creating two cookies with the same name but different attributes to prevent such astonishing result from happening.

Also, your code is using Cookies.remove(name, null). There's no such API in js-cookie as from the latest version, you should using either Cookies.remove(name, attributes) or just Cookies.remove(name).

You're getting the cookie using document.cookie. There's no need to do that. You can use just Cookies.get(name).

Fagner Brack
  • 2,365
  • 4
  • 33
  • 69