简单封装浏览器 cookie 工具类

目前主流浏览器一般都支持 cookie ,以下对 cookie 的操作进行简单封装,以方便使用

主体封装类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { storagePrefix } from 'assets/scripts/config/config'
import { verify, uri } from 'assets/scripts/tools'

/**
 * cookies操作类
 */
export default new class Cookie {
  /**
   * 构造函数
   */
  constructor() {
    this.defaults = {}
    this.expiresMultiplier = 60 * 60 * 24
    this.prefix = storagePrefix
  }

  /**
   * 根据key获取cookie的值
   * @param {string} key 键
   * @returns {object} 值
   */
  get(key) {
    if (!key) {
      throw new Error('没有找到key。')
    }
    if (typeof key === 'object') {
      throw new Error('key不能是一个对象。')
    }
    let cookies = this.all()
    let value = cookies[this.prefix + key]

    try {
      value = JSON.parse(value)
    } catch (e) {
      value = {}
    }
    return value
  }

  /**
   * 设置cookies
   * @param key 键
   * @param value 值
   * @param options 选项
   * @returns {Cookie}
   */
  set(key, value, options) {
    options = verify.isObject(options) ? options : {expires: options}
    let expires = options.expires !== undefined ? options.expires : (this.defaults.expires || '')
    let expiresType = typeof (expires)
    if (expiresType === 'string' && expires !== '') {
      expires = new Date(expires)
    } else if (expiresType === 'number') {
      expires = new Date(+new Date() + 1000 * this.expiresMultiplier * expires)
    }
    if (expires !== '' && 'toGMTString' in expires) {
      expires = ';expires=' + expires.toGMTString()
    }
    let path = options.path || this.defaults.path
    path = path ? ';path=' + path : ''
    let domain = options.domain || this.defaults.domain
    domain = domain ? ';domain=' + domain : ''
    let secure = options.secure || this.defaults.secure ? ';secure' : ''
    if (options.secure === false) secure = ''
    document.cookie = uri.encode(this.prefix + key) + '=' + uri.encode(JSON.stringify(value)) + expires + path + domain + secure
    return this
  }

  /**
   * 删除cookie
   * @param {string||array} keys 删除cookie的key
   * @returns {Cookie}
   */
  remove(keys) {
    keys = verify.isArray(keys) ? keys : [keys]
    for (let i = 0, l = keys.length; i < l; i++) {
      this.set(keys[i], '', -1)
    }
    return this
  }

  /**
   * 获取所有的cookie
   * @returns {object} cookie对象
   */
  all() {
    let cookie = document.cookie
    if (cookie === '') return {}
    let cookieArr = cookie.split('; ')
    let result = {}
    for (let i = 0, l = cookieArr.length; i < l; i++) {
      let item = cookieArr[i].split('=')
      let key = uri.decode(item.shift())
      let value = uri.decode(item.join(''))
      result[key] = value
    }
    return result
  }
}

verify 工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
export default new class Verify {
  // 验证url是否正确,true/false
  isUrl (url) {
    return (/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?/i).test(url)
  }
  
  // 验证手机号码是否正确, true/false
  isTel (tel) {
    return (/^1[3|4|5|8][0-9]\d{4,8}$/).test(tel)
  }
  
  // 判断是否是object对象
  isObject (value) {
    return !!value && Object.prototype.toString.call(value) === '[object Object]'
  }
  
  // 判断是否是数组
  isArray (value) {
    return Object.prototype.toString.call(value) === '[object Array]'
  }
}

uri 工具类

1
2
3
4
5
6
7
8
9
export default new class Uri {
  decode (value) {
    return decodeURIComponent(value)
  }
  
  encode (value) {
    return encodeURIComponent(value)
  }
}

config 基础配置

1
2
// 本地存储的前缀
export const storagePrefix = 'tshark_quick_storage_'