forked from grevory/angular-local-storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocalStorageModule.js
239 lines (209 loc) · 8.59 KB
/
localStorageModule.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
define(['Console'], function (Console) {
"use strict";
Console.group("Entering localStorageService module.");
var service = ['$rootScope', function($rootScope) {
// You should set a prefix to avoid overwriting any local storage variables from the rest of your app
// e.g. angularLocalStorage.constant('prefix', 'yourAppName');
var prefix = 'yourAppName';
// Cookie options (usually in case of fallback)
// expiry = Number of days before cookies expire // 0 = Does not expire
// path = The web path the cookie represents
var cookie = { expiry:30, path: '/'};
// If there is a prefix set in the config lets use that with an appended period for readability
//var prefix = angularLocalStorage.constant;
if (prefix.substr(-1)!=='.') {
prefix = !!prefix ? prefix + '.' : '';
}
// Checks the browser to see if local storage is supported
var browserSupportsLocalStorage = function () {
try {
return ('localStorage' in window && window['localStorage'] !== null);
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
return false;
}
};
// Directly adds a value to local storage
// If local storage is not available in the browser use cookies
// Example use: localStorageService.add('library','angular');
var addToLocalStorage = function (key, value) {
// If this browser does not support local storage use cookies
if (!browserSupportsLocalStorage()) {
$rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
return addToCookies(key, value);
}
// 0 and "" is allowed as a value but let's limit other falsey values like "undefined"
if (!value && value!==0 && value!=="") return false;
try {
localStorage.setItem(prefix+key, value);
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
return addToCookies(key, value);
}
return true;
};
// Directly get a value from local storage
// Example use: localStorageService.get('library'); // returns 'angular'
var getFromLocalStorage = function (key) {
if (!browserSupportsLocalStorage()) {
$rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
return getFromCookies(key);
}
var item = localStorage.getItem(prefix+key);
if (!item) return null;
return item;
};
// Remove an item from local storage
// Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
var removeFromLocalStorage = function (key) {
if (!browserSupportsLocalStorage()) {
$rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
return removeFromCookies(key);
}
try {
localStorage.removeItem(prefix+key);
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
return removeFromCookies(key);
}
return true;
};
// Remove all data for this app from local storage
// Example use: localStorageService.clearAll();
// Should be used mostly for development purposes
var clearAllFromLocalStorage = function () {
if (!browserSupportsLocalStorage()) {
$rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
return clearAllFromCookies();
}
var prefixLength = prefix.length;
for (var key in localStorage) {
// Only remove items that are for this app
if (key.substr(0,prefixLength) === prefix) {
try {
removeFromLocalStorage(key.substr(prefixLength));
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
return clearAllFromCookies();
}
}
}
return true;
};
// Checks the browser to see if cookies are supported
var browserSupportsCookies = function() {
try {
return navigator.cookieEnabled ||
("cookie" in document && (document.cookie.length > 0 ||
(document.cookie = "test").indexOf.call(document.cookie, "test") > -1));
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
return false;
}
};
// Directly adds a value to cookies
// Typically used as a fallback is local storage is not available in the browser
// Example use: localStorageService.cookie.add('library','angular');
var addToCookies = function (key, value) {
if (typeof value == "undefined") return false;
if (!browserSupportsCookies()) {
$rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED');
return false;
}
try {
var expiry = '', expiryDate = new Date();
if (value === null) {
cookie.expiry = -1;
value = '';
}
if (cookie.expiry !== 0) {
expiryDate.setTime(expiryDate.getTime() + (cookie.expiry*24*60*60*1000));
expiry = ", expires="+expiryDate.toGMTString();
}
if (!!key) {
document.cookie = prefix + key + "=" + encodeURIComponent(value) + expiry + ", path="+cookie.path;
}
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error',e.message);
return false;
}
return true;
};
// Directly get a value from a cookie
// Example use: localStorageService.cookie.get('library'); // returns 'angular'
var getFromCookies = function (key) {
if (!browserSupportsCookies()) {
$rootScope.$broadcast('LocalStorageModule.notification.error','COOKIES_NOT_SUPPORTED');
return false;
}
var cookies = document.cookie.split(',');
for(var i=0;i < cookies.length;i++) {
var thisCookie = cookies[i];
while (thisCookie.charAt(0)==' ') {
thisCookie = thisCookie.substring(1,thisCookie.length);
}
if (thisCookie.indexOf(prefix+key+'=') === 0) {
return decodeURIComponent(thisCookie.substring(prefix.length+key.length+1,thisCookie.length));
}
}
return null;
};
var removeFromCookies = function (key) {
addToCookies(key,null);
};
var clearAllFromCookies = function () {
var thisCookie = null, thisKey = null;
var prefixLength = prefix.length;
var cookies = document.cookie.split(';');
for(var i=0;i < cookies.length;i++) {
thisCookie = cookies[i];
while (thisCookie.charAt(0)==' ') {
thisCookie = thisCookie.substring(1,thisCookie.length);
}
key = thisCookie.substring(prefixLength,thisCookie.indexOf('='));
removeFromCookies(key);
}
};
// JSON stringify functions based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON
var stringifyJson = function (vContent, isJSON) {
// If this is only a string and not a string in a recursive run of an object then let's return the string unadulterated
if (typeof vContent === "string" && vContent.charAt(0) !== "{" && !isJSON) {
return vContent;
}
if (vContent instanceof Object) {
var sOutput = "";
if (vContent.constructor === Array) {
for (var nId = 0; nId < vContent.length; sOutput += this.stringifyJson(vContent[nId], true) + ",", nId++);
return "[" + sOutput.substr(0, sOutput.length - 1) + "]";
}
if (vContent.toString !== Object.prototype.toString) { return "\"" + vContent.toString().replace(/"/g, "\\$&") + "\""; }
for (var sProp in vContent) { sOutput += "\"" + sProp.replace(/"/g, "\\$&") + "\":" + this.stringifyJson(vContent[sProp], true) + ","; }
return "{" + sOutput.substr(0, sOutput.length - 1) + "}";
}
return typeof vContent === "string" ? "\"" + vContent.replace(/"/g, "\\$&") + "\"" : String(vContent);
};
var parseJson = function (sJSON) {
if (sJSON.charAt(0)!=='{') {
return sJSON;
}
return eval("(" + sJSON + ")");
};
return {
isSupported: browserSupportsLocalStorage,
add: addToLocalStorage,
get: getFromLocalStorage,
remove: removeFromLocalStorage,
clearAll: clearAllFromLocalStorage,
stringifyJson: stringifyJson,
parseJson: parseJson,
cookie: {
add: addToCookies,
get: getFromCookies,
remove: removeFromCookies,
clearAll: clearAllFromCookies
}
};
}];
Console.groupEnd();
return service;
});