js实现cookie
设置Cookie
在JavaScript中,可以通过document.cookie属性设置Cookie。设置时需要指定键值对以及可选的属性如过期时间、路径、域名等。
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";
读取Cookie
读取Cookie时,document.cookie会返回当前域下的所有Cookie字符串,需要通过字符串处理提取特定值。

function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
console.log(getCookie("username")); // 输出 "John Doe"
删除Cookie
删除Cookie可以通过设置其过期时间为过去的时间实现。

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
设置Cookie属性
Cookie支持以下常用属性:
expires:设置过期时间(UTC格式)。max-age:设置存活时间(秒数)。path:指定Cookie的有效路径。domain:指定Cookie的有效域名。secure:仅通过HTTPS传输。samesite:限制跨站请求携带Cookie。
document.cookie = "token=abc123; max-age=3600; path=/; secure; samesite=strict";
封装Cookie操作
封装常用的Cookie操作方法可以提高代码复用性。
const cookieUtil = {
set(name, value, options = {}) {
let cookie = `${name}=${value}`;
if (options.expires) cookie += `; expires=${options.expires.toUTCString()}`;
if (options.maxAge) cookie += `; max-age=${options.maxAge}`;
if (options.path) cookie += `; path=${options.path}`;
if (options.secure) cookie += `; secure`;
document.cookie = cookie;
},
get(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
return parts.length === 2 ? parts.pop().split(';').shift() : null;
},
delete(name, path = '/') {
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${path}`;
}
};
注意事项
- Cookie有大小限制(通常为4KB),超出部分可能被截断。
- 每个域名下的Cookie数量有限制(通常为20-50个)。
- 敏感信息不建议存储在Cookie中,避免安全风险。
- 现代浏览器支持
HttpOnly属性(仅服务器端可读写),JavaScript无法操作。






