正在加载...

Cookie

Cookie 是浏览器可能附加到匹配网站请求上的短文本。页面写入 theme=dark 并显示 theme / dark;绝不把密码或访问令牌放入 JavaScript 可读取的 Cookie。

不是 Web Storage

上一课的 saved / lida / tea 存在 localStorage。Cookie 只会随匹配网站和路径的请求发送,不会发给每个网站。document.cookie 是分号分隔的字符串,不是对象。

偏好设置

Path=/ 让 theme 在本站路径中可用。SameSite=Lax 限制跨站情形,Secure 仅通过 HTTPS 发送。

Write the theme cookie

javascript
document.cookie = "theme=dark; Path=/; SameSite=Lax; Secure";
console.log(document.cookie);

字符串可能有多个可见键值对,因此不要把整个字符串与 theme=dark 比较。

读取名称

按 ; 分割,找到名称加 =,再对值使用 decodeURIComponent。

Read the theme

javascript
function readCookie(name) {
const start = name + "=";
const pair = document.cookie
.split("; ")
.find((part) => part.startsWith(start));
return pair ? decodeURIComponent(pair.slice(start.length)) : null;
}
console.log(readCookie("theme"));
console.log(readCookie("drink"));

输出先是 dark,再是 null。drink 从未写入,缺少名称不会报错。

编码

; 和 = 是 Cookie 语法。写入 tea / regular 前使用 encodeURIComponent。

读取会得到 tea / regular;原始分号会开启新的部分。

📊 Cookie and localStorage

Bedarf Cookie localStorage
Bei passenden Anfragen oft ja nein
Für Seiten-JavaScript lesbar außer HttpOnly ja
Kleine Präferenz möglich meist einfacher
Sensible Sitzungs-ID Server: HttpOnly + Secure nicht hier speichern

选择

Cookie 和 localStorage 都不能抵御已经在页面运行的 JavaScript,从而保护秘密。

JavaScript 不能设置或读取 HttpOnly;服务器在 Set-Cookie 响应头中发送它。

Page demo — theme cookie

html
<!DOCTYPE html>
<html>
<body>
<p id="line">…</p>
<script>
document.cookie = "theme=dark; Path=/; SameSite=Lax; Secure";
function readCookie(name) {
const start = name + "=";
const pair = document.cookie.split("; ")
.find((part) => part.startsWith(start));
return pair ? decodeURIComponent(pair.slice(start.length)) : null;
}
document.querySelector("#line").textContent =
"theme / " + readCookie("theme");
</script>
</body>
</html>

页面文字

页面保存 dark,读取 theme,再组合文字。

文字是 theme / dark。普通 HTTP 下浏览器可能拒绝 Secure;实际网站使用 HTTPS。

练习

用 Path=/ 写入 theme,读取 drink,编码 tea / regular,说出 HttpOnly、Secure、SameSite,并读出页面文字。

常见错误与总结

不要把 Cookie 当对象或保险箱。敏感会话标识只能由服务器用 HttpOnly、Secure、SameSite 设置。

🧠 测试您的知识

准备开始

测试您的知识

通过这个互动测验挑战自己,看看你对这个主题的理解程度如何

❓
5
问题
🎯
70%
及格要求
♾️
∞
时间
🔄
∞
尝试次数

📝 说明

  • 仔细阅读每个问题
  • 为每个问题选择最佳答案
  • 您可以随时重新参加测验
  • 您的进度将显示在顶部