主题
Cookie
document.cookie 读写当前页面可见的 Cookie。读到的是非 HttpOnly 的 name=value,以分号分隔,不含属性。一次赋值只设置一条,不会清除其他 Cookie。脚本不能设置 HttpOnly。
读取
js
/** 取出当前页面可见的指定 Cookie 值 */
function readCookie(name) {
const prefix = name + '='
const entry = document.cookie
.split(';')
.map((part) => part.trim())
.find((part) => part.startsWith(prefix))
return entry === undefined ? undefined : decodeURIComponent(entry.slice(prefix.length))
}写入
值用 encodeURIComponent。省略 Domain 时为当前主机。
js
document.cookie = 'theme=' + encodeURIComponent('浅色') + '; Path=/; Max-Age=86400; SameSite=Lax'删除
再写同名 Cookie,Path、Domain 与设置时一致,并设 Max-Age=0。
js
document.cookie = 'theme=; Path=/; Max-Age=0; SameSite=Lax'请求携带
浏览器按匹配规则填写 Cookie 请求头。脚本不能手动设置该请求头,也不能从 response.headers 或 XHR 读到 Set-Cookie。
Fetch 的 credentials | 行为 |
|---|---|
omit | 不发送 Cookie,也不处理响应中的 Set-Cookie。 |
same-origin(默认) | 同源请求允许发送和接收 Cookie。 |
include | 跨源请求也允许发送和接收 Cookie,仍受 Cookie 匹配规则和浏览器策略约束。 |
js
await fetch('https://api.example.com/user', {
credentials: 'include',
})js
const xhr = new XMLHttpRequest()
xhr.open('GET', 'https://api.example.com/user')
xhr.withCredentials = true
xhr.send()带凭证的跨源响应需返回明确的 Access-Control-Allow-Origin(不能用 *)和 Access-Control-Allow-Credentials: true,才可向页面脚本开放。跨源预检本身不带 Cookie。
参考 WHATWG Fetch 标准。
