forked from inexorabletash/polyfill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
121 lines (104 loc) · 3.42 KB
/
storage.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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// Storage polyfill by Remy Sharp
// https://gist.github.com/350433
// Needed for IE7-
// Dependencies:
// JSON (use json2.js if necessary)
// Tweaks by Joshua Bell ([email protected])
// * URI-encode item keys
// * Use String() for stringifying
// * added length
if (!window.localStorage || !window.sessionStorage) (function() {
var Storage = function(type) {
function createCookie(name, value, days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
i, c;
for (i = 0; i < ca.length; i++) {
c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
}
function setData(data) {
data = JSON.stringify(data);
if (type == 'session') {
window.name = data;
} else {
createCookie('localStorage', data, 365);
}
}
function clearData() {
if (type == 'session') {
window.name = '';
} else {
createCookie('localStorage', '', 365);
}
}
function getData() {
var data = type == 'session' ? window.name : readCookie('localStorage');
return data ? JSON.parse(data) : {};
}
// initialise if there's already data
var data = getData();
function numKeys() {
var n = 0;
for (var k in data) {
if (data.hasOwnProperty(k)) {
n += 1;
}
}
return n;
}
return {
clear: function() {
data = {};
clearData();
this.length = numKeys();
},
getItem: function(key) {
key = encodeURIComponent(key);
return data[key] === undefined ? null : data[key];
},
key: function(i) {
// not perfect, but works
var ctr = 0;
for (var k in data) {
if (ctr == i) return decodeURIComponent(k);
else ctr++;
}
return null;
},
removeItem: function(key) {
key = encodeURIComponent(key);
delete data[key];
setData(data);
this.length = numKeys();
},
setItem: function(key, value) {
key = encodeURIComponent(key);
data[key] = String(value);
setData(data);
this.length = numKeys();
},
length: 0
};
};
if (!window.localStorage) window.localStorage = new Storage('local');
if (!window.sessionStorage) window.sessionStorage = new Storage('session');
})();