admin管理员组

文章数量:1296885

I'm just curious if document.cookie can ever return undefined.

I read quirksmode's article on cookies and I looked at "Is !document.cookie reliable?" but they don't explicitly answer this question.

Can document.cookie ever be undefined?

I'm just curious if document.cookie can ever return undefined.

I read quirksmode's article on cookies and I looked at "Is !document.cookie reliable?" but they don't explicitly answer this question.

Can document.cookie ever be undefined?

Share Improve this question edited May 23, 2017 at 11:58 CommunityBot 11 silver badge asked Jun 5, 2015 at 18:49 christo8989christo8989 6,8265 gold badges39 silver badges46 bronze badges 5
  • Some of my code that is pulling from cookies was breaking a page on my site. So I'm writing some defensive code and wasn't sure if I needed to account for document.cookie being undefined. – christo8989 Commented Jun 5, 2015 at 18:53
  • 1 No, it's never undefined in browsers that support it, and that's almost every browser in use today. It's also not an ordinary object, but a very special one, with special properties, for instance you can set it's value multiple times without overwriting it. – adeneo Commented Jun 5, 2015 at 18:54
  • that sounds like a problem with using an actual cookie that doesn't exist, not document.cookie itself – CrayonViolent Commented Jun 5, 2015 at 18:55
  • @CrayonViolent Yes but it got me thinking about this. – christo8989 Commented Jun 5, 2015 at 18:57
  • Old question, but this is kind of funny: ...No, it's never undefined in browsers that support it, and that's almost every browser in use today... - Well, if it's ALMOST all browsers, then it CAN be undefined. – Patrick Commented Jun 17, 2019 at 10:29
Add a ment  | 

2 Answers 2

Reset to default 5

The document.cookie property is defined in DOM Level 2, and implemented in every major browser. It sets/gets a string, which may be an empty string (which is falsey, but not undefined).

No.

You can read the spec here http://www.w3/TR/DOM-Level-2-HTML/html.html#ID-8747038

It throws an error if it's set to a value that doesn't adhere to the spec.

本文标签: javascriptIs documentcookie ever undefinedStack Overflow