Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

javascript - Can't access cookies from document.cookie in JS, but browser shows cookies exist

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

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;

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:

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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 });

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...