🍪
JavaScript Cookie 完全指南
编程小白也能理解的Cookie知识点汇总
🍪 什么是Cookie?
想象一下,你去一家咖啡店,店员给你一张会员卡,记录了你喜欢的咖啡口味和积分。下次你去的时候,店员看到这张卡就知道你的喜好了。
在网页世界中,Cookie就是这张”会员卡”。它是网站存储在用户浏览器中的小型文本文件,用来记录用户的信息。
简单说: Cookie是网站留在你浏览器里的小纸条,帮你记住登录状态、购物车内容、个性化设置等信息。
❓ 为什么需要Cookie?
HTTP协议本身是”无状态”的,这意味着每次你访问网站,服务器都把你当作新用户。Cookie解决了这个问题:
主要用途:
- 会话管理:记住登录状态,不用每次访问都重新登录
- 个性化:保存用户偏好设置(如语言、主题)
- 跟踪:记录用户行为进行分析(广告商常用)
- 购物车:在电商网站保存已选商品
注意: Cookie不是程序,不能执行代码,也不会传播病毒。它们只是纯文本文件。
🧩 Cookie的基本结构
一个Cookie由多个部分组成,就像一张会员卡上有不同信息区域:
// 一个典型的Cookie示例
“username=JohnDoe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/; domain=.example.com; Secure; SameSite=Lax”
“username=JohnDoe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/; domain=.example.com; Secure; SameSite=Lax”
组成部分详解:
- 名称=值:核心数据(如 username=JohnDoe)
- expires:过期时间(不设置则关闭浏览器就消失)
- path:Cookie生效的路径(如 /products)
- domain:Cookie生效的域名
- Secure:仅在HTTPS连接下发送
- SameSite:防止跨站请求伪造(Lax/Strict/None)
🛠️ 如何用JavaScript创建Cookie?
在JavaScript中,我们可以通过设置document.cookie
属性来创建Cookie。
// 创建一个简单的Cookie
document.cookie = “username=JohnDoe”;
// 创建带过期时间的Cookie(7天后过期)
let date = new Date();
date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
document.cookie = `userTheme=dark; expires=${date.toUTCString()}`;
// 创建安全Cookie(仅HTTPS可用)
document.cookie = “sessionId=abc123; Secure”;
document.cookie = “username=JohnDoe”;
// 创建带过期时间的Cookie(7天后过期)
let date = new Date();
date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
document.cookie = `userTheme=dark; expires=${date.toUTCString()}`;
// 创建安全Cookie(仅HTTPS可用)
document.cookie = “sessionId=abc123; Secure”;
动手试试:
🔍 如何读取Cookie?
读取Cookie很简单,但有点小麻烦:所有Cookie都打包在一个字符串里,需要自己解析。
// 获取所有Cookie
const allCookies = document.cookie;
// 输出: “username=JohnDoe; userTheme=dark; sessionId=abc123”
// 解析Cookie的函数(常用)
function getCookie(name) {
const cookies = document.cookie.split(‘;’);
for(let cookie of cookies) {
const [cookieName, cookieValue] = cookie.trim().split(‘=’);
if(cookieName === name) {
return cookieValue;
}
}
return null; // 没找到
}
// 使用示例
const theme = getCookie(‘userTheme’); // 返回 “dark”
const allCookies = document.cookie;
// 输出: “username=JohnDoe; userTheme=dark; sessionId=abc123”
// 解析Cookie的函数(常用)
function getCookie(name) {
const cookies = document.cookie.split(‘;’);
for(let cookie of cookies) {
const [cookieName, cookieValue] = cookie.trim().split(‘=’);
if(cookieName === name) {
return cookieValue;
}
}
return null; // 没找到
}
// 使用示例
const theme = getCookie(‘userTheme’); // 返回 “dark”
读取当前页面的Cookie:
🔄 修改和删除Cookie
修改Cookie其实就是用相同的名称创建一个新Cookie覆盖旧的。删除则是设置一个过期时间为过去的时间。
// 修改Cookie
// 只需重新设置同名Cookie
document.cookie = “username=JaneSmith”;
// 删除Cookie
// 设置过期时间为过去的时间
document.cookie = “username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;”;
// 只需重新设置同名Cookie
document.cookie = “username=JaneSmith”;
// 删除Cookie
// 设置过期时间为过去的时间
document.cookie = “username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;”;
操作Cookie:
⚠️ Cookie的注意事项
大小限制
每个Cookie最大约4KB,每个域名下的Cookie数量有限制(通常20-50个)
安全性
Cookie可能被窃取(XSS攻击),所以:
- 敏感信息不要存Cookie
- 使用Secure标志(仅HTTPS)
- 使用HttpOnly标志(防止JavaScript访问)
- 考虑使用SameSite属性
隐私法规
GDPR等隐私法规要求在使用非必要Cookie前需获得用户同意
替代方案
现代开发中,常使用替代方案:
- Web Storage:localStorage和sessionStorage(存储空间更大)
- IndexedDB:大型结构化数据存储
- 服务端Session:敏感信息存服务器
💡 实际应用示例
下面是一个简单的主题切换功能,使用Cookie记住用户选择的主题:
// 页面加载时检查Cookie并应用主题
window.onload = function() {
const theme = getCookie(‘theme’) || ‘light’;
document.body.className = theme + ‘-theme’;
}
// 切换主题的函数
function switchTheme(newTheme) {
// 应用新主题
document.body.className = newTheme + ‘-theme’;
// 保存到Cookie(有效期1年)
const date = new Date();
date.setFullYear(date.getFullYear() + 1);
document.cookie = `theme=${newTheme}; expires=${date.toUTCString()}`;
}
window.onload = function() {
const theme = getCookie(‘theme’) || ‘light’;
document.body.className = theme + ‘-theme’;
}
// 切换主题的函数
function switchTheme(newTheme) {
// 应用新主题
document.body.className = newTheme + ‘-theme’;
// 保存到Cookie(有效期1年)
const date = new Date();
date.setFullYear(date.getFullYear() + 1);
document.cookie = `theme=${newTheme}; expires=${date.toUTCString()}`;
}