How do you delete all the cookies for the current domain using JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
After testing almost ever method listed in multiple style of browsers on multiple styles of cookies, I found almost nothing here works even 50%.
Please help correct as needed, but I'm going to throw my 2 cents in here. The following method breaks everything down and basically builds the cookie value string based on both the settings pieces as well as including a step by step build of the path string, starting with
/
of course.Hope this helps others and I hope any criticism may come in the form of perfecting this method. At first I wanted a simple 1-liner as some others sought, but JS cookies are one of those things not so easily dealt with.
Note that this code has two limitations:
HttpOnly
flag set, as theHttpOnly
flag disables Javascript's access to the cookie.Path
value. (This is despite the fact that those cookies will appear indocument.cookie
, but you can't delete it without specifying the samePath
value with which it was set.)As far as I know there's no way to do a blanket delete of any cookie set on the domain. You can clear a cookie if you know the name and if the script is on the same domain as the cookie.
You can set the value to empty and the expiration date to somewhere in the past:
There's an excellent article here on manipulating cookies using javascript.
Jquery:
vanilla JS
And here's one to clear all cookies in all paths and all variants of the domain (www.mydomain.com, mydomain.com etc):