Reading cookie expiration date

前端 未结 7 1176
我在风中等你
我在风中等你 2020-11-28 11:50

Is it possible to read cookie expiration date using JavaScript?

If yes, how? If not, is there a source I can look at?

7条回答
  •  感动是毒
    2020-11-28 12:12

    There is a work-around to OP's question if you also control the setting of the cookies. I do it like this:

    function setCookie(name, value, expiryInDays) {
      const d = new Date();
      d.setTime(d.getTime() + expiryInDays * 24 * 60 * 60 * 1000);
    
      document.cookie = `${name}=${value}_${d.toUTCString()};expires=${d.toUTCString()}`;
    }
    
    function showCookies() {
      if (document.cookie.length !== 0) {
        const allCookies = document.cookie.split(/;\s*/);
        const wrapper = document.getElementById('allCookies');
    
        wrapper.innerHTML = allCookies.reduce((html, cookie, index) => {
          const cookieParts = cookie.split('=');
          const cookieValueParts = cookieParts[1].split('_');
          const cookieHtml = [
            `${index + 1}`,
            `Cookie name: ${cookieParts[0]}`,
            `Cookie value: ${cookieValueParts[0]}`,
            `Expires: ${cookieValueParts[1] || 'unknown'}`
          ].join('
    '); return html + `

    ${cookieHtml}

    `; }, ''); } }
    
    

提交回复
热议问题