原生JS操作cookie 基于es6 es5版本请自行修改

网上查阅了很多关于document.cookie操作的文章 基本都是实现了一部分或者不是使用最新的接口实现的,于是自己整理了一套。

/**
* @description 格式化cookie选项
* @param Obj
*/
function formatCookie(Obj = {}) {
  const objKeys = Object.keys(Obj);
  if (objKeys.length < 1) return '';

  let str = '';

  objKeys.map(item => {
    const value = Obj[item];
    value && (str += `;${item}=${value}`);
  });
  return str;
}

/**
* @description js原生设置cookie
* @param Obj
* @param {String} Obj.name 给你要设置的cookie起个名字(key)
* @param {String} Obj.value cookie的具体内容(value)
* @param {String} Obj.maxAge 设置cookie的相对过期时间,单位:s
* @param {String} Obj.expire 设置cookie的绝对过期时间(国际标准时间),单位:s
* @param {Boolean} Obj.secure 设置cookie是否只通过https传输
*/
function setCookie(Obj = {}) {
  if (!Obj.name) return '';

  const cookieStr = `${Obj.name}=${Obj.value}` + formatCookie({
    'path': Obj.path || '',
    'max-age': Obj.maxAge || 0,
    'expires': Obj.expire || ''
  });

  Obj.secure === true && (cookieStr += ';secure');
  document.cookie = cookieStr;
}

/**
* @description js原生获取指定cookie
* @param name 获取指定cookie
*/
function getCookie(name) {
  const cookies = document.cookie;
  if (!cookies) return '';

  const oCookie = {};
  const cookieArr = cookies.split(';');
  for (item of cookieArr) {
    const index = item.indexOf('=');
    oCookie[item.slice(0, index).trim()] = item.slice(index + 1);
  }

  return oCookie[name];
}

/**
* @description js原生删除指定cookie
* @param name
*/
function removeCookie(name) {
  setCookie({
    name,
    value: '',
    maxAge: -1
  });
};

// maxAge调用示例
setCookie({
  name: 'test',
  value: 'test',
  maxAge: 10 // 单位s
});

// expire调用示例
let ex = new Date();
ex.setSeconds(100);
setCookie({
  name: 'test',
  value: 'test',
  expire: ex.toUTCString()
});

// 仅https传输调用示例
setCookie({
  name: 'test',
  value: 'test',
  maxAge: 10, // 单位s
  secure: true
});

参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/cookie

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值