How do I create and read a value from cookie?

2018-12-31 00:32发布

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

16条回答
无与为乐者.
2楼-- · 2018-12-31 00:50

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 (opts.days) { 
            opts['max-age'] = opts.days * 60 * 60 * 24; 
            delete opts.days 
            }
        opts = Object.entries(opts).reduce((str, [k, v]) => `${str}; ${k}=${v}`, '')
        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);
查看更多
君临天下
3楼-- · 2018-12-31 00:52

Mozilla provides a simple framework for reading and writing cookies with full unicode support along with examples of how to use it.

Once included on the page, you can set a cookie:

docCookies.setItem(name, value);

read a cookie:

docCookies.getItem(name);

or delete a cookie:

docCookies.removeItem(name);

For example:

// sets a cookie called 'myCookie' with value 'Chocolate Chip'
docCookies.setItem('myCookie', 'Chocolate Chip');

// reads the value of a cookie called 'myCookie' and assigns to variable
var myCookie = docCookies.getItem('myCookie');

// removes the cookie called 'myCookie'
docCookies.removeItem('myCookie');

See more examples and details on Mozilla's document.cookie page.

查看更多
只若初见
4楼-- · 2018-12-31 00:52

I use this object. Values are encoded, so it's necessary to consider it when reading or writing from server side.

cookie = (function() {

/**
 * Sets a cookie value. seconds parameter is optional
 */
var set = function(name, value, seconds) {
    var expires = seconds ? '; expires=' + new Date(new Date().getTime() + seconds * 1000).toGMTString() : '';
    document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
};

var map = function() {
    var map = {};
    var kvs = document.cookie.split('; ');
    for (var i = 0; i < kvs.length; i++) {
        var kv = kvs[i].split('=');
        map[kv[0]] = decodeURIComponent(kv[1]);
    }
    return map;
};

var get = function(name) {
    return map()[name];
};

var remove = function(name) {
    set(name, '', -1);
};

return {
    set: set,
    get: get,
    remove: remove,
    map: map
};

})();
查看更多
其实,你不懂
5楼-- · 2018-12-31 00:55

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);
      }
   }
}
查看更多
不流泪的眼
6楼-- · 2018-12-31 00:57

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/

查看更多
刘海飞了
7楼-- · 2018-12-31 00:57

I've used js-cookie to success.

<script src="/path/to/js.cookie.js"></script>
<script>
  Cookies.set('foo', 'bar');
  Cookies.get('foo');
</script>
查看更多
登录 后发表回答