封装cookies的set与get方法

const cookies = {
  defaultConfig: {
    expires: '1d',
    path: '; path=/',
    domain: '',
    secure: '',
    sameSite: '; SameSite=Lax'
  },
  get: function(key) {
    var value = decodeURIComponent(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURIComponent(key).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null;

    if (value && value.substring(0, 1) === '{' && value.substring(value.length - 1, value.length) === '}') {
      try {
        value = JSON.parse(value);
      } catch (e) {
        return value;
      }
    }
    return value;
  },
  set: function(key, value, expireTimes, path, domain, secure, sameSite) {
    if (!key) {
      throw new Error('Cookie name is not find in first argument.');
    } else if (/^(?:expires|max\-age|path|domain|secure|SameSite)$/i.test(key)) {
      throw new Error('Cookie key name illegality, Cannot be set to ["expires","max-age","path","domain","secure","SameSite"]\t current key name: ' + key);
    }
    // support json object
    if (value && value.constructor === Object) {
      value = JSON.stringify(value);
    }
    var _expires = '';
    expireTimes = expireTimes == undefined ? this.defaultConfig.expires : expireTimes;
    if (expireTimes && expireTimes != 0) {
      switch (expireTimes.constructor) {
        case Number:
          if (expireTimes === Infinity || expireTimes === -1) _expires = '; expires=Fri, 31 Dec 9999 23:59:59 GMT';
          else _expires = '; max-age=' + expireTimes;
          break;
        case String:
          if (/^(?:\d+(y|m|d|h|min|s))$/i.test(expireTimes)) {
            // get capture number group
            var _expireTime = expireTimes.replace(/^(\d+)(?:y|m|d|h|min|s)$/i, '$1');
            // get capture type group , to lower case
            switch (expireTimes.replace(/^(?:\d+)(y|m|d|h|min|s)$/i, '$1').toLowerCase()) {
              // Frequency sorting
              case 'm':
                _expires = '; max-age=' + +_expireTime * 2592000;
                break; // 60 * 60 * 24 * 30
              case 'd':
                _expires = '; max-age=' + +_expireTime * 86400;
                break; // 60 * 60 * 24
              case 'h':
                _expires = '; max-age=' + +_expireTime * 3600;
                break; // 60 * 60
              case 'min':
                _expires = '; max-age=' + +_expireTime * 60;
                break; // 60
              case 's':
                _expires = '; max-age=' + _expireTime;
                break;
              case 'y':
                _expires = '; max-age=' + +_expireTime * 31104000;
                break; // 60 * 60 * 24 * 30 * 12
              default:
                new Error('unknown exception of "set operation"');
            }
          } else {
            _expires = '; expires=' + expireTimes;
          }
          break;
        case Date:
          _expires = '; expires=' + expireTimes.toUTCString();
          break;
      }
    }
    document.cookie =
      encodeURIComponent(key) + '=' + encodeURIComponent(value) +
      _expires +
      (domain ? '; domain=' + domain : this.defaultConfig.domain) +
      (path ? '; path=' + path : this.defaultConfig.path) +
      (secure == undefined ? this.defaultConfig.secure : secure ? '; Secure' : '') +
      (sameSite == undefined ? this.defaultConfig.sameSite : (sameSite ? '; SameSite=' + sameSite : ''));
    return this;
  },
  remove: function(key, path, domain) {
    if (!key || !this.isKey(key)) {
      return false;
    }
    document.cookie = encodeURIComponent(key) +
      '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' +
      (domain ? '; domain=' + domain : this.defaultConfig.domain) +
      (path ? '; path=' + path : this.defaultConfig.path) +
      '; SameSite=Lax';
    return this;
  },
  isKey: function(key) {
    return (new RegExp('(?:^|;\\s*)' + encodeURIComponent(key).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=')).test(document.cookie);
  }
}
export default cookies

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_陌默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值