如何在JavaScript中创建和读取cookie的值?


当前回答

对于那些需要保存{foo: 'bar'}这样的对象的人,我分享了我编辑过的@KevinBurke的答案。我添加了JSON。stringify和JSON。解析,仅此而已。

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;
    }

}

现在你可以这样做:

cookie.set('cookie_key', {foo: 'bar'}, 30);

cookie.get('cookie_key'); // {foo: 'bar'}

cookie.set('cookie_key', 'baz', 30);

cookie.get('cookie_key'); // 'baz'

其他回答

一种厚脸皮的、简单的读取cookie的方法可能是这样的:

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

如果您知道您的cookie包含以下内容,则可以使用此方法:用户名="John Doe";id = 123;。注意,字符串在cookie中需要引号。可能不是推荐的方法,但对测试/学习有效。

我用这个物体。值是经过编码的,所以在从服务器端读写时必须考虑到这一点。

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
};

})();

在ES6中读取cookie的简单方法。

function getCookies() {
    var cookies = {};
    for (let cookie of document.cookie.split('; ')) {
        let [name, value] = cookie.split("=");
        cookies[name] = decodeURIComponent(value);
    }
    console.dir(cookies);
}

我用js-cookie取得了成功。

<script src="/path/to/js.cookie.js"></script>
<script>
  Cookies.set('foo', 'bar');
  Cookies.get('foo');
</script>

ES7,使用正则表达式的get()。基于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)

用法- Cookie。Get (name, value [, options]): Options支持所有标准cookie选项,并增加了“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.

其他答案使用“expires”而不是“max-age”来支持旧的IE版本。这个方法需要ES7,所以IE7已经出来了(这不是什么大问题)。

注意:像“=”和“{:}”这样有趣的字符被支持作为cookie值,regex处理开头和结尾的空白(来自其他库)。 如果您想存储对象,可以在和JSON之前或之后对它们进行编码。stringify和JSON。解析、编辑上面的内容,或者添加另一个方法。例如:

Cookie.getJSON = name => JSON.parse(Cookie.get(name))
Cookie.setJSON = (name, value, opts) => Cookie.set(name, JSON.stringify(value), opts);