无法在JS中访问document.cookie中的Cookie,但浏览器显示Cookie [英] Can't access cookies from document.cookie in JS, but browser shows cookies exist

查看:2033
本文介绍了无法在JS中访问document.cookie中的Cookie,但浏览器显示Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从JavaScript存取任何Cookie。我需要读取一些值,并通过JSON为我的自定义检查发送他们。

I can't access any cookie from JavaScript. I need to read some value and send them via JSON for my custom checks.

我试图访问来自JS的cookie,如下所述:

I've tried to access cookies from JS, like it was described at:

  • http://www.w3schools.com/js/js_cookies.asp
  • Javascript get cookie by name

正如您在代码中可以看到的,它看起来像水晶一样清晰: / p>

As you can see at the code, it's seen as clear as a crystal the next:

var c_value = document.cookie;

当我尝试访问 document.cookie 值来自Chrome的网络调试器,我只能在观察表达式中看到空字符串:

When I'm trying to access the document.cookie value from the Chrome's web-debugger, I see only the empty string at the Watch expressions:

Cookie值,我需要。

So I can't read cookies value, which I need.

我检查了cookie名称,我发送以获得关联的值是正确的。
此外,如果您有兴趣,但我使用 W3Schools 源代码获取Cookie(但是从第二个链接,技术类似)。

I've checked the cookie name, which I'm sending to get an associated value IS correct. Also, I'm using the W3Schools source code for getting cookies, if you're interested (but from the 2nd link, the technique is similar).

如何解决我的问题?

谢谢!

推荐答案

您最有可能处理 httponly Cookie。 httponly 是可以在Cookie上设置的标志,表示它们无法通过JavaScript访问。这是为了防止恶意脚本窃取敏感数据或甚至整个会话的Cookie。

You are most likely dealing with httponly cookies. httponly is a flag you can set on cookies meaning they can not be accessed by JavaScript. This is to prevent malicious scripts stealing cookies with sensitive data or even entire sessions.

因此您必须禁用 httponly flag或者你需要找到另一种方式来获取你的javascript的数据。

So you either have to disable the httponly flag or you need to find another way to get the data to your javascript.

通过查看你的代码,应该很容易禁用http only标志: / p>

By looking at your code it should be easy to disable the http only flag:

Response.AddHeader("Set-Cookie", "CookieName=CookieValue; path=/;");
Response.SetCookie(new HttpCookie("session-id") { Value = Guid.NewGuid().ToString(), HttpOnly = false });
Response.SetCookie(new HttpCookie("user-name") { Value = data.Login, HttpOnly = false });

现在您应该可以从JavaScript访问Cookie信息。但是我不知道你想要得到什么样的数据,所以也许你可以去另一种方法,例如在页面上显示一些数据属性,你需要的信息,而不是试图读取cookie:

Now you should be able to access the cookie information from JavaScript. However I don't know exactly what kind of data you are trying to get so maybe you can go for another approach instead and for example render some data attribute on the page with the information you need instead of trying to read the cookie:

<div id="example" data-info="whatever data you are trying to retrieve"></div>



console.log(document.getElementById('example').getAttribute('data-info'));

这篇关于无法在JS中访问document.cookie中的Cookie,但浏览器显示Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆