问题
This is related to my other question, i'm asking a new question as i've narrowed down the problem and the original question was getting rather convoluted.
In a nutshell, i have a cookie that refuses to be deleted!
My server sets the cookie "session=abc; domain=example.com; path=/;"
I want to edit this cookie client-side, so lets say i want to change abc to xyz then i run the following code
document.cookie = "session=xyz; domain=example.com; path=/;"
Now, when i inspect the cookies i actually now have the following two cookies (note the leading dot):
"session=abc; domain=example.com; path=/;"
"session=xyz; domain=.example.com; path=/;"
I quickly gave up trying to force my new cookie to drop the dot, and instead opted to delete the existing cookie before setting a new cookie.
However, this:
document.cookie = 'session=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
and this:
document.cookie = 'session=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/; domain=example.com;';
Both do absolutely nothing
How on earth am i supposed to delete a cookie, when i can't even get the domains to match up?
NB
Whilst writing this question, things have gotten more complicated! I have just noticed that the above behaviour only happens on a specific page, if i attempt to delete the server's cookie from another page it disappears without a fuss
To add insult to injury This actually works as expected in IE/Edge
回答1:
I know you don't want to use dependencies unless necessary, but JS-Cookie is an extremely lightweight, extensively tested library that is cross compatible; it shouldn't affect performance and could be exactly what you're looking for
Here's a link to the GitHub repo.
Cheers!
回答2:
Use jQuery cookie library instead of accessing document.cookie directly https://plugins.jquery.com/cookie/
Then just use it like jQuery.cookie('session','xyz',{ path: '/' });
回答3:
This was solved by removing the domain altogether!
document.cookie = 'session=xyz; path=/; domain=;";
Hope this helps someone else, as this has been an absolute bitch to diagnose
EDIT
So in a cruel twist of fate, this does indeed fix the issue for chrome and firefox, but you guessed it - IE/Edge is now throwing the toys out of the pram!
I give up
来源:https://stackoverflow.com/questions/46026665/javascript-cookie-absolutely-refuses-to-be-deleted