关于cookie的汉字怎么转码

988 阅读1分钟
//cooies.js

/*
 * 校验是否空字符串
 * val(string):字符串
 */
function isNotEmptyString(val) {
  return typeof val === 'string' && val !== ''
}

/*
 * 获取cookie
 * name(string):cookie键名
 */
export function getCookie(name) {
  let ret
  let m
  if (isNotEmptyString(name)) {
    if ((m = String(document.cookie).match(new RegExp('(?:^| )' + name + '(?:(?:=([^;]*))|;|$)')))) {
      ret = m[1] ? decodeURIComponent(m[1]) : ''
    }
  }
  return ret
}

/*
 * 设置cookie
 * name(string):cookie键名
 * val(string):cookie键值,最终种到cookie里的值为encode
 * expires(number):过期天数
 * domain(string):作用域
 * path(string):作用pathname
 * secure(string):安全域
 */
export function setCookie(name, val, expires, domain, path, secure) {
  let text = String(encodeURIComponent(val))
  let date = expires
  // 从当前时间开始,多少天后过期
  if (typeof date === 'number') {
    date = new Date()
    date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000)
  }
  // expiration date
  if (date instanceof Date) {
    text += '; expires=' + date.toUTCString()
  }
  // domain
  if (isNotEmptyString(domain)) {
    text += '; domain=' + domain
  }
  // path
  if (isNotEmptyString(path)) {
    text += '; path=' + path
  }
  // secure
  if (secure) {
    text += '; secure'
  }
  document.cookie = `"${name}=${text}"`
}


/*
 * 删除cookie
 * name(string):cookie键名
 * domain(string):作用域
 * path(string):作用pathname
 * secure(string):安全域
 */
export function removeCookie(name, domain, path, secure) {
  setCookie(name, '', -1, domain, path, secure)
}