Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete a cookie from a specific domain using Javascript?

Let's say I am at http://www.example.com and I want to delete a cookie whose domain is .example.com and another one whose domain is www.example.com.

I am currently using this generic function :

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

which only seems to be removing cookies whose domain is www.example.com.

But how can I specify so that it also removes cookies whose domain is .example.com ?

EDIT : Basically I'm looking for a function that can delete all cookies related to http://www.example.com as long as they don't have the httponly flag. Is there such a function?

like image 310
The Random Guy Avatar asked Jul 21 '13 21:07

The Random Guy


People also ask

How do you delete a cookie in JavaScript?

Delete a Cookie with JavaScript You don't have to specify a cookie value when you delete a cookie. Just set the expires parameter to a past date: document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; You should define the cookie path to ensure that you delete the right cookie.

Can I delete specific cookies?

Under the Browsing history section, select Settings. In the Website Data Settings dialog box, select View files. Scroll through the list of cookies to find the one you want to delete. Select a cookie and press Delete on the keyboard.

Can JavaScript delete HttpOnly cookie?

By setting many cookies, an application can cause the browser to remove old cookies. This even works from JavaScript, and it also removes HttpOnly cookies. So by setting many cookies, it is possible for a script to remove HttpOnly cookies.


1 Answers

You could do this only if you were at http://example.com and wanted to delete http://blah.example.com cookie. It wouldn't work from www.example.com either - only the "base" domain can delete subdomain cookies.

There are also "all-subdomain" cookies, which start with a ., and can also only be deleted by the base domain.

From the base domain, this should work to delete it:

document.cookie = 'my_cookie=; path=/; domain=.example.com; expires=' + new Date(0).toUTCString();

Or using the excellent jquery.cookie plugin:

$.cookie('my_cookie',null, {domain:'.example.com'})
like image 149
Kevin Avatar answered Sep 26 '22 01:09

Kevin