How do I create and read a value from cookie?

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

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

相关标签:
19条回答
  • 2020-11-21 05:04

    I have written simple cookieUtils, it has three functions for creating the cookie, reading the cookie and deleting the cookie.

    var CookieUtils = {
        createCookie: function (name, value, expireTime) {
            expireTime = !!expireTime ? expireTime : (15 * 60 * 1000); // Default 15 min
            var date = new Date();
            date.setTime(date.getTime() + expireTime);
            var expires = "; expires=" + date.toGMTString();
            document.cookie = name + "=" + value + expires + "; path=/";
        },
        getCookie: function (name) {
            var value = "; " + document.cookie;
            var parts = value.split("; " + name + "=");
            if (parts.length == 2) {
                return parts.pop().split(";").shift();
            }
        },
        deleteCookie: function(name) {
            document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        }
    };
    
    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 2020-11-21 05:07

    JQuery Cookies

    or plain Javascript:

    function setCookie(c_name,value,exdays)
    {
       var exdate=new Date();
       exdate.setDate(exdate.getDate() + exdays);
       var c_value=escape(value) + ((exdays==null) ? "" : ("; expires="+exdate.toUTCString()));
       document.cookie=c_name + "=" + c_value;
    }
    
    function getCookie(c_name)
    {
       var i,x,y,ARRcookies=document.cookie.split(";");
       for (i=0; i<ARRcookies.length; i++)
       {
          x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
          y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
          x=x.replace(/^\s+|\s+$/g,"");
          if (x==c_name)
          {
            return unescape(y);
          }
       }
    }
    
    0 讨论(0)
  • 2020-11-21 05:07

    I've used accepted answer of this thread many times already. It's great piece of code: Simple and usable. But I usually use babel and ES6 and modules, so if you are like me, here is code to copy for faster developing with ES6

    Accepted answer rewritten as module with ES6:

    export const createCookie = ({name, value, days}) => {
      let expires;
      if (days) {
        let date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = '; expires=' + date.toGMTString();
      } else {
        expires = '';
      }
      document.cookie = name + '=' + value + expires + '; path=/';
    };
    
    export const getCookie = ({name}) => {
      if (document.cookie.length > 0) {
        let c_start = document.cookie.indexOf(name + '=');
        if (c_start !== -1) {
          c_start = c_start + name.length + 1;
          let c_end = document.cookie.indexOf(';', c_start);
          if (c_end === -1) {
            c_end = document.cookie.length;
          }
          return unescape(document.cookie.substring(c_start, c_end));
        }
      }
      return '';
    };
    

    And after this you can simply import it as any module (path of course may vary):

    import {createCookie, getCookie} from './../helpers/Cookie';
    
    0 讨论(0)
  • 2020-11-21 05:08

    Here are functions you can use for creating and retrieving cookies.

    function createCookie(name, value, days) {
        var expires;
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        else {
            expires = "";
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    }
    
    function getCookie(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) {
                    c_end = document.cookie.length;
                }
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    }
    
    0 讨论(0)
  • 2020-11-21 05:11

    Here's a code to Get, Set and Delete Cookie in JavaScript.

    function getCookie(name) {
        name = name + "=";
        var cookies = document.cookie.split(';');
        for(var i = 0; i <cookies.length; i++) {
            var cookie = cookies[i];
            while (cookie.charAt(0)==' ') {
                cookie = cookie.substring(1);
            }
            if (cookie.indexOf(name) == 0) {
                return cookie.substring(name.length,cookie.length);
            }
        }
        return "";
    }
    
    function setCookie(name, value, expirydays) {
     var d = new Date();
     d.setTime(d.getTime() + (expirydays*24*60*60*1000));
     var expires = "expires="+ d.toUTCString();
     document.cookie = name + "=" + value + "; " + expires;
    }
    
    function deleteCookie(name){
      setCookie(name,"",-1);
    }

    Source: http://mycodingtricks.com/snippets/javascript/javascript-cookies/

    0 讨论(0)
提交回复
热议问题