forked from quasarframework/quasar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcookies.js
More file actions
98 lines (80 loc) · 2.02 KB
/
cookies.js
File metadata and controls
98 lines (80 loc) · 2.02 KB
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
import Utils from '../utils'
function encode (string) {
return encodeURIComponent(string)
}
function decode (string) {
return decodeURIComponent(string)
}
function stringifyCookieValue (value) {
return encode(value === Object(value) ? JSON.stringify(value) : '' + value)
}
function read (string) {
if (string === '') {
return string
}
if (string.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
string = string.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\')
}
// Replace server-side written pluses with spaces.
// If we can't decode the cookie, ignore it, it's unusable.
// If we can't parse the cookie, ignore it, it's unusable.
string = decode(string.replace(/\+/g, ' '))
try {
string = JSON.parse(string)
}
catch (e) {}
return string
}
function set (key, val, opts = {}) {
let time = opts.expires
if (typeof opts.expires === 'number') {
time = new Date()
time.setMilliseconds(time.getMilliseconds() + opts.expires * 864e+5)
}
document.cookie = [
encode(key), '=', stringifyCookieValue(val),
time ? '; expires=' + time.toUTCString() : '', // use expires attribute, max-age is not supported by IE
opts.path ? '; path=' + opts.path : '',
opts.domain ? '; domain=' + opts.domain : '',
opts.secure ? '; secure' : ''
].join('')
}
function get (key) {
let
result = key ? undefined : {},
cookies = document.cookie ? document.cookie.split('; ') : [],
i = 0,
l = cookies.length,
parts,
name,
cookie
for (; i < l; i++) {
parts = cookies[i].split('=')
name = decode(parts.shift())
cookie = parts.join('=')
if (!key) {
result[name] = cookie
}
else if (key === name) {
result = read(cookie)
break
}
}
return result
}
function remove (key, options) {
set(key, '', Utils.extend(true, {}, options, {
expires: -1
}))
}
function has (key) {
return get(key) !== undefined
}
export default {
get,
set,
has,
remove,
all: () => get()
}