欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js设置cookie有效期,并获取存储的cookie值

程序员文章站 2022-05-19 11:58:43
...
// 设置cookie,setTime是用来设置有效期,下边代码expires为30时代表有效期30分钟
  setCookie: function (cname, value, expires) {
    let date = new Date()
    date.setTime(date.getTime() + expires * 60 * 1000)
    document.cookie = cname + '=' + escape(value) + ';expires=' + date.toUTCString()
  },
  // 获取cookie,传入key以获取value
  getCookie: function (cname) {
    if (document.cookie.length > 0) {
      let cstart = document.cookie.indexOf(cname + '=')
      if (cstart !== -1) {
        cstart = cstart + cname.length + 1
        let cend = document.cookie.indexOf(';', cstart)
        if (cend === -1) {
          cend = document.cookie.length
        }
        return unescape(document.cookie.substring(cstart, cend))
      }
    }
    return ''
  },

 

相关标签: cookie javascript