JavaScript设置Cookie过期时间不生效,无法30分钟自动过期如何解决
问题根因
- Cookie的
expires属性要求传入符合RFC 7231规范的GMT/UTC格式完整时间字符串,你当前使用的date.toTimeString()仅返回包含时分秒和时区信息的局部时间格式,浏览器无法识别该格式作为过期时间,因此该配置直接被忽略。
修复后代码
const cookieButton = document.getElementById('store-cookie') cookieButton.addEventListener('click', e => { const input = document.getElementById('fav-cookie').value let date = new Date() const minutes = 30 date.setTime(date.getTime() + (minutes * 60 * 1000)) // 替换toTimeString为toUTCString,同时对输入内容编码、可选添加path配置 document.cookie = `favCookie=${encodeURIComponent(input)}; expires=${date.toUTCString()}; path=/;` })
补充说明
- 新增
encodeURIComponent()处理输入值,避免输入内容包含分号、空格、中文等特殊字符时,Cookie存储格式出错 - 可选添加
path=/配置,让生成的Cookie在站点所有路径下均可访问,默认仅当前页面路径可用
内容的提问来源于stack exchange,提问作者Dylan Welzel
相关产品推荐
相关产品推荐

