forked from andris9/jStorage
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjstorage.js
293 lines (264 loc) · 8.37 KB
/
jstorage.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/**
* ----------------------------- JSTORAGE -------------------------------------
* Simple local storage wrapper to save data on the browser side, supporting
* all major browsers - IE6+, Firefox2+, Safari4+, Chrome4+ and Opera 10.5+
*
* Copyright (c) 2010 Andris Reinman, [email protected]
* Project homepage: www.jstorage.info
*
* Licensed under MIT-style license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* USAGE:
*
* jStorage requires Prototype, MooTools or jQuery! If jQuery is used, then
* jQuery-JSON (http://code.google.com/p/jquery-json/) is also needed.
* (jQuery-JSON needs to be loaded BEFORE jStorage!)
*
* Methods:
*
* -set(key, value)
* $.jStorage.set(key, value) -> saves a value
*
* -get(key[, default])
* value = $.jStorage.get(key [, default]) ->
* retrieves value if key exists, or default if it doesn't
*
* -deleteKey(key)
* $.jStorage.deleteKey(key) -> removes a key from the storage
*
* -flush()
* $.jStorage.flush() -> clears the cache
*
* -backendType()
* $.jStorage.backendType() ->
* the name of the backend being used or an empty string if none could be
* found. Values are "localStorage", "globalStorage", "userData",
* "Google Gears", or "". It can be used as a Boolean to determine if
* storage will be persistent.
*
* <value> can be any JSON-able value, including objects and arrays.
*
*/
(function($){
if(!$ || !($.toJSON || Object.toJSON || window.JSON)){
throw new Error("jQuery, MooTools or Prototype needs to be loaded before jStorage!");
}
var
/* This is the object, that holds the cached values */
_storage = {},
/* Actual browser storage (localStorage or globalStorage['domain']) */
_storage_service = {jStorage:"{}"},
/* Name of the back end used (empty string if storage will not persist) */
_backend_type = "",
/* DOM element for older IE versions, holds userData behavior */
_storage_elm = null,
/* Used by Google Gears */
_storage_db = null,
/* function to encode objects to JSON strings */
json_encode = $.toJSON || Object.toJSON || (window.JSON && (JSON.encode || JSON.stringify)),
/* function to decode objects from JSON strings */
json_decode = $.evalJSON || (window.JSON && (JSON.decode || JSON.parse)) || function(str){
return String(str).evalJSON();
};
////////////////////////// PRIVATE METHODS ////////////////////////
/**
* Initialization function. Detects if the browser supports DOM Storage
* or userData behavior and behaves accordingly.
* @returns undefined
*/
function _init(){
/* Check if browser supports localStorage */
if(window.localStorage){
try {
_storage_service = window.localStorage;
_backend_type = "localStorage";
} catch(E0) {/* Firefox fails when touching localStorage and cookies are disabled */}
}
/* Check if browser supports globalStorage */
else if(window.globalStorage){
try {
_storage_service = window.globalStorage[window.location.hostname];
_backend_type = "globalStorage";
} catch(E1) {/* Firefox fails when touching localStorage and cookies are disabled */}
}
/* Check if browser supports userData behavior */
else {
_storage_elm = document.createElement('link');
if(_storage_elm.addBehavior){
_backend_type = "userData";
/* Use a DOM element to act as userData storage */
_storage_elm.style.behavior = 'url(#default#userData)';
/* userData element needs to be inserted into the DOM! */
document.getElementsByTagName('head')[0].appendChild(_storage_elm);
_storage_elm.load("jStorage");
var data = "{}";
try{
data = _storage_elm.getAttribute("jStorage");
}catch(E2){}
_storage_service.jStorage = data;
}else{
_storage_elm = null;
}
}
if (!_backend_type && (window.google && google.gears)){
_storage_db = google.gears.factory.create("beta.database");
_storage_db.open("jStorage");
_storage_db.execute("create table if not exists jStorage (k text primary key, v text)").close();
var result = _storage_db.execute("select k, v from jStorage");
while (result.isValidRow()){
_storage[result.field(0)] = json_decode(result.field(1));
result.next();
}
result.close();
_backend_type = "Google Gears";
}
/* if jStorage string is retrieved, then decode it */
else if(_storage_service.jStorage){
try{
_storage = json_decode(String(_storage_service.jStorage));
}catch(E3){_storage_service.jStorage = "{}";}
}else{
_storage_service.jStorage = "{}";
}
}
/**
* This functions provides the "save" mechanism to store the jStorage object
* @returns undefined
*/
function _save(){
try{
_storage_service.jStorage = json_encode(_storage);
// If userData is used as the storage engine, additional
if(_storage_elm) {
_storage_elm.setAttribute("jStorage",_storage_service.jStorage);
_storage_elm.save("jStorage");
}
}catch(E4){/* probably cache is full, nothing is saved this way*/}
}
/**
* Function checks if a key is set and is string or numberic
*/
function _checkKey(key){
if(!key || (typeof key != "string" && typeof key != "number")){
throw new TypeError('Key name must be string or numeric');
}
return true;
}
////////////////////////// PUBLIC INTERFACE /////////////////////////
$.jStorage = {
/* Version number */
version: "0.1.3",
/**
* Sets a key's value.
*
* @param {String} key - Key to set. If this value is not set or not
* a string an exception is raised.
* @param value - Value to set. This can be any value that is JSON
* compatible (Numbers, Strings, Objects etc.).
* @returns the used value
*/
set: function(key, value){
_checkKey(key);
_storage[key] = value;
_save();
if (_storage_db){
_storage_db.execute("replace into jStorage values (?, ?)",
[String(key), json_encode(value)]).close();
}
return value;
},
/**
* Looks up a key in cache
*
* @param {String} key - Key to look up.
* @param {mixed} def - Default value to return, if key didn't exist.
* @returns the key value, default value or <null>
*/
get: function(key, def){
_checkKey(key);
if(key in _storage){
return _storage[key];
}
return typeof(def) == 'undefined' ? null : def;
},
/**
* Deletes a key from cache.
*
* @param {String} key - Key to delete.
* @returns true if key existed or false if it didn't
*/
deleteKey: function(key){
_checkKey(key);
if(key in _storage){
delete _storage[key];
_save();
if (_storage_db){
_storage_db.execute("delete from jStorage where k = ?",
[String(key)]).close();
}
return true;
}
return false;
},
/**
* Deletes everything in cache.
*
* @returns true
*/
flush: function(){
_storage = {};
_save();
/*
* Just to be sure - andris9/jStorage#3
*/
if (window.localStorage){
try{
localStorage.clear();
}catch(E5){}
}
if (_storage_db){
_storage_db.execute("delete from jStorage").close();
}
return true;
},
/**
* Returns a read-only copy of _storage
*
* @returns Object
*/
storageObj: function(){
function F() {}
F.prototype = _storage;
return new F();
},
/**
* Returns the type of back-end storage used for persistence as
* one of the strings "localStorage", "globalStorage", "userData",
* "Google Gears", or "" if no back end could be found (and data
* can't be persistently stored).
*
* @returns String
*/
backendType: function(){
return _backend_type;
}
};
// Initialize jStorage
_init();
})(window.jQuery || window.$);