如何从cookie创建和读取值?

时间:2011-01-28 06:58:01

标签: javascript cookies

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

23 个答案:

答案 0 :(得分:219)

以下是可用于创建和检索Cookie的功能。

var createCookie = function(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 "";
}

答案 1 :(得分:39)

JQuery Cookies

或普通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);
      }
   }
}

答案 2 :(得分:36)

简约且功能齐全的ES6方法:

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

答案 3 :(得分:14)

Mozilla提供simple framework for reading and writing cookies with full unicode support以及如何使用它的示例。

一旦包含在页面上,您就可以设置一个cookie:

docCookies.setItem(name, value);

读取cookie:

docCookies.getItem(name);

或删除Cookie:

docCookies.removeItem(name);

例如:

// 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');

查看有关Mozilla's document.cookie page的更多示例和详细信息。

答案 4 :(得分:6)

我已经多次使用过这个帖子的接受答案了。这是一段很棒的代码:简单易用。但我通常使用babel和ES6和模块,所以如果你像我一样,这里是复制的代码,以便用ES6更快地开发

Accepted answer重写为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 '';
};

在此之后,您只需将其导入为任何模块(当然路径可能会有所不同):

import {createCookie, getCookie} from './../helpers/Cookie';

答案 5 :(得分:6)

对于那些需要像{foo:'bar'}这样的保存对象的人,我分享了@ KevinBurke答案的编辑版本。我添加了JSON.stringify和JSON.parse,这就是全部。

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'

答案 6 :(得分:5)

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

用法 - Cookie.get(name,value [,options]):
options支持所有标准cookie选项,并添加&#34; days&#34;:

  • 路径:&#39; /&#39; - 任何绝对路径。 默认:当前文档位置
  • :&#39; sub.example.com&#39; - 可能不是以dot开头。 默认:没有子域的当前主机。
  • 安全:true - 仅通过https提供Cookie。 默认:false。
  • :2天,直到Cookie过期。 默认:会话结束。
    设置过期的其他方法:
    • 到期:&#39; Sun,2018年2月18日16:23:42 GMT&#39; - 作为GMT字符串的到期日期 当前日期可以使用:new Date(Date.now())。toUTCString()
    • &#39; max-age&#39; :30 - 与天数相同,但以秒为单位,而不是几天。

其他答案使用&#34;到期&#34;而不是&#34; max-age&#34;支持旧的IE版本。这种方法需要ES7,因此IE7无论如何都是不合适的(这不是什么大问题)。

注意:有趣的字符,如&#34; =&#34;和&#34; {:}&#34;作为cookie值支持,正则表达式处理前导和尾随空格(来自其他库) 如果您想存储对象,可以使用和JSON.stringify和JSON.parse之前和之后对它们进行编码,编辑上面的内容,或添加其他方法。例如:

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

答案 7 :(得分:4)

以下是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);
}

来源:http://mycodingtricks.com/snippets/javascript/javascript-cookies/

答案 8 :(得分:2)

我使用这个对象。值是编码的,因此在从服务器端读取或写入时需要考虑它。

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

})();

答案 9 :(得分:1)

我喜欢这种使用现代 JavaScript 读取 cookie 的单行解决方案:

let cookies = Object.fromEntries(document.cookie.split(';').map(i=>i.trim().split('=')));

现在你有了一个带有键和值的 JavaScript 对象。

答案 10 :(得分:0)

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

答案 11 :(得分:0)

我已将js-cookie用于成功。

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

答案 12 :(得分:0)

您可以使用我的cookie ES module获取/设置/删除Cookie。

用法:

在您的head标签中,包含以下代码:

<script src="https://raw.githack.com/anhr/cookieNodeJS/master/build/cookie.js"></script>

<script src="https://raw.githack.com/anhr/cookieNodeJS/master/build/cookie.min.js"></script>

现在,您可以使用window.cookie在网页中存储用户信息。

cookie.isEnabled()

您的网络浏览器是否启用了cookie?

returns {boolean} true if cookie enabled.

示例

if ( cookie.isEnabled() )
    console.log('cookie is enabled on your browser');
else
    console.error('cookie is disabled on your browser');

cookie.set(名称,值)

设置cookie。

name: cookie name.
value: cookie value.

示例

cookie.set('age', 25);

cookie.get(name [,defaultValue]);

获取Cookie。

name: cookie name.
defaultValue: cookie default value. Default is undefined.
returns cookie value or defaultValue if cookie was not found
var age = cookie.get('age', 25);

cookie.remove(name);

删除Cookie。

name: cookie name.
cookie.remove( 'age' );

Example of usage

答案 13 :(得分:0)

简单阅读

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

答案 14 :(得分:0)

我使用以下功能,这些功能是我从各种渠道获得的最好的功能编写的,并清除了一些错误或差异。

setCookie函数没有高级选项,只是简单的东西,但是代码易于理解,这总是一个加号:

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

答案 15 :(得分:0)

chrome小组提出了一种新的方法,用于管理与Cookie存储API异步的cookie(从版本87开始在Google Chrome中可用):https://wicg.github.io/cookie-store/

今天已将其与polyfill用于其他浏览器:https://github.com/mkay581/cookie-store

// load polyfill
import 'cookie-store';

// set a cookie
await cookieStore.set('name', 'value');
// get a cookie
const savedValue = await cookieStore.get('name');

答案 16 :(得分:0)

使用模板字面量的非常短的 ES6 函数。请注意,您需要自己对值进行编码/解码,但它可以开箱即用,用于更简单的目的,例如存储版本号。

await axios.post(...)

答案 17 :(得分:0)

通过类似于 sessionStoragelocalStorage 的界面:

const cookieStorage = {
  getItem: (key) {
    const cookies = document.cookie.split(';')
      .map(cookie => cookie.split('='))
      .reduce(
        (accumulation, [key, value]) => ({...accumulation, [key.trim()]: value}),
        {}
      )
    
    return cookies[key]
  },
  setItem: (key, value) {
    document.cookie = `${key}=${value}`
  },
}

它的用法 cookieStorage.setItem('', '')cookieStorage.getItem('')

答案 18 :(得分:-1)

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user=getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
}

答案 19 :(得分:-1)

我写了简单的cookieUtils,它具有创建cookie,读取cookie和删除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;';
    }
};

答案 20 :(得分:-1)

一种轻松而简单的读取cookie的方式可能类似于:

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

如果您知道Cookie包含类似username="John Doe"; id=123;的内容,则可以使用此选项。请注意,字符串将需要在cookie中加引号。可能不是推荐的方法,但是可以用于测试/学习。

答案 21 :(得分:-1)

以下是w3chools中提到的示例。

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

答案 22 :(得分:-1)

readCookie的改进版本:

function readCookie( name )
{
    var cookieParts = document.cookie.split( ';' )
    ,   i           = 0
    ,   part
    ,   part_data
    ,   value
    ;

    while( part = cookieParts[ i++ ] )
    {
        part_data = part.split( '=' );

        if ( part_data.shift().replace(/\s/, '' ) === name )
        {
            value = part_data.shift();
            break;
        }

    }
    return value;
}

一旦找到您的cookie值并返回其值,这应该会中断。在我看来,双重分裂非常优雅。

if条件的替换是空格修剪,以确保它正确匹配