forked from simple-login/app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocal-storage-polyfill.js
76 lines (76 loc) · 2.09 KB
/
local-storage-polyfill.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
// From https://stackoverflow.com/a/12302790/1428034
window.store = {
localStoreSupport: function () {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
},
set: function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else {
var expires = "";
}
if (this.localStoreSupport()) {
localStorage.setItem(name, value);
}
else {
document.cookie = name + "=" + value + expires + "; path=/";
}
},
get: function (name) {
if (this.localStoreSupport()) {
var ret = localStorage.getItem(name);
//console.log(typeof ret);
switch (ret) {
case 'true':
return true;
case 'false':
return false;
default:
return ret;
}
}
else {
// cookie fallback
/*
* after adding a cookie like
* >> document.cookie = "bar=test; expires=Thu, 14 Jun 2018 13:05:38 GMT; path=/"
* the value of document.cookie may look like
* >> "foo=value; bar=test"
*/
var nameEQ = name + "="; // what we are looking for
var ca = document.cookie.split(';'); // split into separate cookies
for (var i = 0; i < ca.length; i++) {
var c = ca[i]; // the current cookie
while (c.charAt(0) == ' ') c = c.substring(1, c.length); // remove leading spaces
if (c.indexOf(nameEQ) == 0) { // if it is the searched cookie
var ret = c.substring(nameEQ.length, c.length);
// making "true" and "false" a boolean again.
switch (ret) {
case 'true':
return true;
case 'false':
return false;
default:
return ret;
}
}
}
return null; // no cookie found
}
},
del: function (name) {
if (this.localStoreSupport()) {
localStorage.removeItem(name);
}
else {
this.set(name, "", -1);
}
},
}