document.cookie 通过在赋值字符串中附加 expires 或 max-age 属性来控制有效期。不写任何有效期,则默认为会话 Cookie,浏览器关闭后自动清除。
expires:指定过期时间点
const d = new Date();
d.setTime(d.getTime() + 7 * 24 * 60 * 60 * 1000); // 7天后
document.cookie = "token=abc123; expires=" + d.toUTCString() + "; path=/";
expires 的值必须是 UTC 格式时间字符串(toUTCString() 输出符合要求)。兼容性好,适合需要支持老浏览器的场景。
max-age:指定存活秒数
// 设置 7 天后过期
document.cookie = "token=abc123; max-age=" + (7 * 24 * 60 * 60) + "; path=/";
// 设置 30 分钟后过期
document.cookie = "session=xyz; max-age=1800; path=/";
max-age 单位是秒,语义更直观,是现代浏览器推荐用法。max-age 优先级高于 expires,两者同时存在时以 max-age 为准。
删除 Cookie
本质是将有效期设为过去:
// 方法一:max-age=0 立即过期
document.cookie = "token=; max-age=0; path=/";
// 方法二:expires 设为历史时间
document.cookie = "token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
常见坑
path 不一致无法删除
设置时用了 path=/,删除时也必须带上相同的 path:
// 错误:path 不匹配,删除失败
document.cookie = "token=; max-age=0";
// 正确
document.cookie = "token=; max-age=0; path=/";
domain 不一致无法删除
.example.com 和 sub.example.com 是不同 domain,设置与删除必须一致。
HttpOnly Cookie 前端无权操作
带 HttpOnly 标志的 Cookie 在 document.cookie 中不可见,只能由服务端通过 Set-Cookie 响应头设置和清除。
实用封装
function setCookie(name, value, days) {
const d = new Date();
d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${encodeURIComponent(value)}; expires=${d.toUTCString()}; path=/`;
}
function getCookie(name) {
return document.cookie
.split('; ')
.find(row => row.startsWith(name + '='))
?.split('=')[1];
}
function deleteCookie(name) {
document.cookie = `${name}=; max-age=0; path=/`;
}
使用示例:
setCookie('token', 'abc123', 7); // 7天有效期
getCookie('token'); // 'abc123'
deleteCookie('token');
如果需要跨子域共享 Cookie,添加 domain=.example.com;HTTPS 环境下建议同时设置 Secure; SameSite=Strict。
