How do I create and read a value from cookie?

前端 未结 19 1622
梦如初夏
梦如初夏 2020-11-21 04:42

How can I create and read a value from a cookie in JavaScript?

19条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 05:05

    Minimalistic and full featured ES6 approach:

    const setCookie = (name, value, days = 7, path = '/') => {
      const expires = new Date(Date.now() + days * 864e5).toUTCString()
      document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=' + path
    }
    
    const getCookie = (name) => {
      return document.cookie.split('; ').reduce((r, v) => {
        const parts = v.split('=')
        return parts[0] === name ? decodeURIComponent(parts[1]) : r
      }, '')
    }
    
    const deleteCookie = (name, path) => {
      setCookie(name, '', -1, path)
    }
    

提交回复
热议问题