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


当前回答

chrome团队提出了一种新的方式管理Cookie与Cookie存储API异步(可在谷歌chrome从版本87开始):https://wicg.github.io/cookie-store/

今天已经在其他浏览器中使用了它: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');

其他回答

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

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

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

const getCookie = (cookieName) => {
  return (document.cookie.match(`(^|;) *${cookieName}=([^;]*)`)||[])[2]
}
  
const setCookie = (cookieName, value, days=360, path='/') => {
  let expires = (new Date(Date.now()+ days*86400*1000)).toUTCString();
  document.cookie = `${cookieName}=${value};expires=${expires};path=${path};`
}

const deleteCookie = (cookieName) => {
  document.cookie = `${cookieName}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;`;
}  

我用js-cookie取得了成功。

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

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

用法:

在你的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>

现在你可以使用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');

饼干。集合(名称,值)

设置一个饼干。

name: cookie name.
value: cookie value.

例子

cookie.set('age', 25);

饼干。get(name[, defaultValue]);

吃块饼干。

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

饼干。移除(名称);

删除cookie。

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

用法示例