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

查看:51
本文介绍了无法从 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:

正如你在代码中看到的,它看起来像水晶一样清晰:

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

var c_value = document.cookie;

当我尝试从 Chrome 的网络调试器访问 document.cookie 值时,我只看到 Watch 表达式 处的空字符串:

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).

我该如何解决我的问题?

How can I fix my issue?

推荐答案

您很可能正在处理 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 标志,要么需要找到另一种方法将数据获取到您的 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 标志应该很容易:

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天全站免登陆