Javascript 如何从 cookie 创建和读取值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4825683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:17:38  来源:igfitidea点击:

How do I create and read a value from cookie?

javascriptcookies

提问by Venkatesh Appala

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

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

采纳答案by Venkatesh Appala

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

以下是可用于创建和检索 cookie 的函数。

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

回答by artnikpro

Minimalistic and full featured ES6 approach:

简约且功能齐全的 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)
}

回答by Paul McCowat

JQuery Cookies

jQuery 饼干

or plain Javascript:

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

回答by Brendan Nee

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

Mozilla 提供了一个简单的框架来读取和写入具有完全 unicode 支持的 cookie以及如何使用它的示例。

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

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

docCookies.setItem(name, value);

read a cookie:

读取 cookie:

docCookies.getItem(name);

or delete a cookie:

或删除一个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.

Mozilla 的 document.cookie 页面上查看更多示例和详细信息。

A version of this simple js file is on github.

这个简单的 js 文件的一个版本在 github 上

回答by SamGoody

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

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)

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

用法 - Cookie.get(name, value [, options]):
options 支持所有标准 cookie 选项并添加“天”:

  • 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.
  • 路径:'/' - 任何绝对路径。默认值:当前文档位置,
  • domain: 'sub.example.com' - 不能以点开头。默认值:没有子域的当前主机。
  • 安全: true - 仅通过 https 提供 cookie。默认值:假。
  • days: 2 - cookie 到期前的天数。默认:会话结束。
    设置过期的其他方法:
    • expires: 'Sun, 18 Feb 2018 16:23:42 GMT' - 作为 GMT 字符串的到期日期。
      当前日期可以使用: new Date(Date.now()).toUTCString()
    • 'max-age': 30 - 与天相同,但以秒而不是天为单位。

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

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

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 值,并且正则表达式处理前导和尾随空格(来自其他库)。
如果您想存储对象,请在使用 JSON.stringify 和 JSON.parse 前后对它们进行编码,编辑以上内容,或添加其他方法。例如:

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

回答by Angel

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.

对于那些需要保存像 {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;
    }

}

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'

回答by Lukas Liesis

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

我已经多次使用该线程的已接受答案。这是一段很棒的代码:简单且可用。但我通常使用babel和 ES6 和模块,所以如果你和我一样,这里是复制代码以更快地使用 ES6 开发

Accepted answerrewritten as module with ES6:

接受的答案用 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';

回答by Shubham Kumar

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

这是在 JavaScript 中获取、设置和删除 Cookie的代码。

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/

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

回答by sinuhepop

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

})();

回答by Andrej

You can use my cookie ES modulefor get/set/remove cookie.

您可以使用我的cookie ES 模块来获取/设置/删除 cookie。

Usage:

用法:

In your head tag, include the following code:

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

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

or

或者

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

Now you can use window.cookie for store user information in web pages.

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

cookie.isEnabled()

cookie.isEnabled()

Is the cookie enabled in your web browser?

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

returns {boolean} true if cookie enabled.

Example

例子

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

cookie.set( name, value )

cookie.set( 名称, 值 )

Set a cookie.

设置一个cookie。

name: cookie name.
value: cookie value.

Example

例子

cookie.set('age', 25);

cookie.get( name[, defaultValue] );

cookie.get( name[, defaultValue] );

get a 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.remove( 名称 );

Remove cookie.

删除饼干。

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

Example of usage

使用示例