forked from marcuswestin/store.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cookieStorage.js
61 lines (52 loc) · 1.44 KB
/
cookieStorage.js
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
// cookieStorage is useful Safari private browser mode, where localStorage
// doesn't work but cookies do. This implementation is adopted from
// https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
var util = require('../src/util')
var Global = util.Global
var trim = util.trim
module.exports = {
name: 'cookieStorage',
read: read,
write: write,
each: each,
remove: remove,
clearAll: clearAll,
}
var doc = Global.document
function read(key) {
if (!key || !_has(key)) { return null }
var regexpStr = "(?:^|.*;\\s*)" +
escape(key).replace(/[\-\.\+\*]/g, "\\$&") +
"\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"
return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1"))
}
function each(callback) {
var cookies = doc.cookie.split(/; ?/g)
for (var i = cookies.length - 1; i >= 0; i--) {
if (!trim(cookies[i])) {
continue
}
var kvp = cookies[i].split('=')
var key = unescape(kvp[0])
var val = unescape(kvp[1])
callback(val, key)
}
}
function write(key, data) {
if(!key) { return }
doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"
}
function remove(key) {
if (!key || !_has(key)) {
return
}
doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"
}
function clearAll() {
each(function(_, key) {
remove(key)
})
}
function _has(key) {
return (new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie)
}