How do I delete a cookie from a specific domain us

2019-03-20 05:33发布

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?

2条回答
欢心
2楼-- · 2019-03-20 06:15

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'})
查看更多
女痞
3楼-- · 2019-03-20 06:20

For security, you're not allowed to edit (or delete) a cookie on another site. Since there's no guarantee that you own both foo.domain.com and bar.domain.com, you won't be allowed to edit the cookies of foo.domain.com from bar.domain.com and vice versa.

Consider if you were allowed to do that and went to a malicious site, then back to your bank where you were about to deposit a cheque into your bank account. But while being on the malicious site, they updated your bank cookie with their own bank information. Now, suddenly, the cheque would be deposited into the malicious site's owner's bank account.

查看更多
登录 后发表回答