You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 13:45:03