Why can't I expire a cookie with JavaScript (not HttpOnly)

吃可爱长大的小学妹 提交于 2019-12-11 08:09:47

问题


I've got a cookie being set in a framework I'm developing within via JavaScript (the framework appears to be using https://github.com/carhartl/jquery-cookie). I'm developing within this framework but don't have access to the framework code and I want to delete a cookie via JavaScript (I do not have access to anything serverside within this framework).

Inspecting the cookie via Chrome, I can tell a lot about it:

"domain": "www.example.com", 
"expirationDate": 1667235180, 
"hostOnly": true, 
"httpOnly": false, 
"name": "my_cookie", 
"path": "/", 
"secure": false, 
"session": false, 
"storeId": "0", 
"value": "123456789"

It is hostOnly, but that should be fine as I am trying to remove from the same domain set in the domain field.

I'm trying to remove it using the following code:

function clearCookie(name, domain, path) {
      var domain = domain || document.domain;
      var path = path || "/";
      document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

clearCookie('my_cookie', 'www.example.com', '/');

When I do this however, it creates a new session cookie with a domain of ".www.example.com" (note the extra period) and doesn't delete the current cookie.

What am I missing?


回答1:


I think there's a problem with how you're setting the expiration. Setting cookies with JavaScript requires a UTC/GMT format for the date. See this related answer:

Which date formats can I use when specifying the expiry date when setting a cookie?




回答2:


Old question, but I just ran into this and discovered the issue.

If you have a hostOnly cookie, do not specify the domain when you modify/expire it.

Most cookie handling libraries will auto-specify the domain if one is not provided, making it difficult, if not impossible, to edit a hostOnly cookie.




回答3:


You can't actually delete a cookie via javascript. What you do is set the existing cookie to expire and then allow the browser to handle its destruction. If you check the jquery-cookie source you can see that it actually has a function to destroy cookies that you could use here to simplify things.

The simple answer here is to use the existing frameworks remove function.

$.removeCookie(key)


来源:https://stackoverflow.com/questions/15482743/why-cant-i-expire-a-cookie-with-javascript-not-httponly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!