本文介绍了为什么我无法使用JavaScript过期Cookie(不是HttpOnly)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我通过JavaScript开发的框架中设置了一个cookie(该框架似乎使用)。我在这个框架内开发,但没有访问框架代码,我想通过JavaScript删除一个cookie(我没有访问任何服务器在这个框架内)。



通过Chrome检查Cookie,我可以说明很多:

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

这是hostOnly,但应该很好,因为我想从同一个域中删除

 >  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','/');

但是,当我这样做时,会创建一个新的会话Cookie,其域名为.www.example .com(注意额外的时间段),并且不会删除当前的Cookie。



我缺少什么?

解决方案

与您如何设置到期。使用JavaScript设置Cookie需要UTC / GMT格式的日期。请参阅相关答案:




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?

解决方案

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?

这篇关于为什么我无法使用JavaScript过期Cookie(不是HttpOnly)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 14:50