Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Javascript document.cookie always returns empty string

I have this real strange problem with client side javascript setting cookies. I'm developing a little 1 page demo at the moment to use cookies to store some 'preferences'. Please note that I can't use a server side language for this demo or any 3rd party jQuery plugins.

So I've written a javascript object to set a cookie:

var cookie = {
  set: function (name,value,exdays) {

    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var value = escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=name + "=" + value;
    console.log(document.cookie);
  }
}

cookie.set('foo','bar',2);
console.log(document.cookie);

It just returns an empty string. I've gone into Chrome console to see if I can do it via directly modifying document.cookie

> document.cookie = "foo=bar";
"foo=bar"
> document.cookie
""

How do you set a cookie via client side javascript?

Edit: I am not in incognito mode and cookies are enabled.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

HttpOnly cookies cannot be accessed from Javascript and session cookies are usually set as HttpOnly cookies. See also this StackOverflow question: How to read a secure cookie using JavaScript

So... check whether the cookie you want to read has the 'HttpOnly' flag set... If so, you know the culprit. It's not a bug, it's a feature!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...