UNPKG

1.48 kBJavaScriptView Raw
1// cookieStorage is useful Safari private browser mode, where localStorage
2// doesn't work but cookies do. This implementation is adopted from
3// https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
4
5var util = require('../src/util')
6var Global = util.Global
7var trim = util.trim
8
9module.exports = {
10 name: 'cookieStorage',
11 read: read,
12 write: write,
13 each: each,
14 remove: remove,
15 clearAll: clearAll,
16}
17
18var doc = Global.document
19
20function read(key) {
21 if (!key || !_has(key)) { return null }
22 var regexpStr = "(?:^|.*;\\s*)" +
23 escape(key).replace(/[\-\.\+\*]/g, "\\$&") +
24 "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"
25 return unescape(doc.cookie.replace(new RegExp(regexpStr), "$1"))
26}
27
28function each(callback) {
29 var cookies = doc.cookie.split(/; ?/g)
30 for (var i = cookies.length - 1; i >= 0; i--) {
31 if (!trim(cookies[i])) {
32 continue
33 }
34 var kvp = cookies[i].split('=')
35 var key = unescape(kvp[0])
36 var val = unescape(kvp[1])
37 callback(val, key)
38 }
39}
40
41function write(key, data) {
42 if(!key) { return }
43 doc.cookie = escape(key) + "=" + escape(data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"
44}
45
46function remove(key) {
47 if (!key || !_has(key)) {
48 return
49 }
50 doc.cookie = escape(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"
51}
52
53function clearAll() {
54 each(function(_, key) {
55 remove(key)
56 })
57}
58
59function _has(key) {
60 return (new RegExp("(?:^|;\\s*)" + escape(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(doc.cookie)
61}