How do I create and read a value from cookie?

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

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

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

    A cheeky and simple way of reading a cookie could be something like:

    let username, id; 
    eval(document.cookie); 
    console.log(username + ", " + id); // John Doe, 123
    

    This could be used if you know your cookie contains something like: username="John Doe"; id=123;. Note that a string would need quotes in the cookie. Not the recommended way probably, but works for testing/learning.

    0 讨论(0)
  • 2020-11-21 05:13

    A simple read

    var getCookie = function (name) {
        var valueStart = document.cookie.indexOf(name + "=") + name.length + 1;
        var valueEnd = document.cookie.indexOf(";", valueStart); 
        return document.cookie.slice(valueStart, valueEnd)
    }
    
    0 讨论(0)
  • 2020-11-21 05:15

    I've used js-cookie to success.

    <script src="/path/to/js.cookie.js"></script>
    <script>
      Cookies.set('foo', 'bar');
      Cookies.get('foo');
    </script>
    
    0 讨论(0)
  • 2020-11-21 05:16

    I use the following functions, which I have written by taking the best I have found from various sources and weeded out some bugs or discrepancies.

    The function setCookie does not have advanced options, just the simple stuff, but the code is easy to understand, which is always a plus:

    function setCookie(name, value, daysToLive = 3650) { // 10 years default
      let cookie = name + "=" + encodeURIComponent(value);
      if (typeof daysToLive === "number") {
        cookie += "; max-age=" + (daysToLive * 24 * 60 * 60);
        document.cookie = cookie + ";path=/";
      }
    }
    function getCookie(name) {
      let cookieArr = document.cookie.split(";");
      for (let i = 0; i < cookieArr.length; i++) {
        let cookiePair = cookieArr[i].split("=");
        if (name == cookiePair[0].trim()) {
          return decodeURIComponent(cookiePair[1].trim());
        }
      }
      return undefined;
    }
    function deleteCookie(name) {
      setCookie(name, '', -1);
    }
    
    0 讨论(0)
  • 2020-11-21 05:19

    ES7, using a regex for get(). Based on MDN

    const Cookie = {
        get: name => {
            let c = document.cookie.match(`(?:(?:^|.*; *)${name} *= *([^;]*).*$)|^.*$`)[1]
            if (c) return decodeURIComponent(c)
        },
        set: (name, value, opts = {}) => {
            /*If options contains days then we're configuring max-age*/
            if (opts.days) {
                opts['max-age'] = opts.days * 60 * 60 * 24;
    
                /*Deleting days from options to pass remaining opts to cookie settings*/
                delete opts.days 
            }
    
            /*Configuring options to cookie standard by reducing each property*/
            opts = Object.entries(opts).reduce(
                (accumulatedStr, [k, v]) => `${accumulatedStr}; ${k}=${v}`, ''
            )
    
            /*Finally, creating the key*/
            document.cookie = name + '=' + encodeURIComponent(value) + opts
        },
        delete: (name, opts) => Cookie.set(name, '', {'max-age': -1, ...opts}) 
        // path & domain must match cookie being deleted 
    }
    

    Cookie.set('user', 'Jim', {path: '/', days: 10}) 
    // Set the path to top level (instead of page) and expiration to 10 days (instead of session)
    

    Usage - Cookie.get(name, value [, options]):
    options supports all standard cookie options and adds "days":

    • path: '/' - any absolute path. Default: current document location,
    • domain: 'sub.example.com' - may not start with dot. Default: current host without subdomain.
    • secure: true - Only serve cookie over https. Default: false.
    • days: 2 - days till cookie expires. Default: End of session.
      Alternative ways of setting expiration:
      • expires: 'Sun, 18 Feb 2018 16:23:42 GMT' - date of expiry as a GMT string.
        Current date can be gotten with: new Date(Date.now()).toUTCString()
      • 'max-age': 30 - same as days, but in seconds instead of days.

    Other answers use "expires" instead of "max-age" to support older IE versions. This method requires ES7, so IE7 is out anyways (this is not a big deal).

    Note: Funny characters such as "=" and "{:}" are supported as cookie values, and the regex handles leading and trailing whitespace (from other libs).
    If you would like to store objects, either encode them before and after with and JSON.stringify and JSON.parse, edit the above, or add another method. Eg:

    Cookie.getJSON = name => JSON.parse(Cookie.get(name))
    Cookie.setJSON = (name, value, opts) => Cookie.set(name, JSON.stringify(value), opts);
    
    0 讨论(0)
  • 2020-11-21 05:22

    For those who need save objects like {foo: 'bar'}, I share my edited version of @KevinBurke's answer. I've added JSON.stringify and JSON.parse, that's all.

    cookie = {
    
        set: function (name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else
                var expires = "";
            document.cookie = name + "=" + JSON.stringify(value) + expires + "; path=/";
        },
    
        get : function(name){
            var nameEQ = name + "=",
                ca = document.cookie.split(';');
    
            for(var i=0;i < ca.length;i++) {
              var c = ca[i];
              while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) 
                  return  JSON.parse(c.substring(nameEQ.length,c.length));
            }
    
            return null;
        }
    
    }
    

    So, now you can do things like this:

    cookie.set('cookie_key', {foo: 'bar'}, 30);
    
    cookie.get('cookie_key'); // {foo: 'bar'}
    
    cookie.set('cookie_key', 'baz', 30);
    
    cookie.get('cookie_key'); // 'baz'
    
    0 讨论(0)
提交回复
热议问题