-
Notifications
You must be signed in to change notification settings - Fork 3
/
ssw.js
514 lines (394 loc) · 12.2 KB
/
ssw.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/*
* Session Storage Wrapper - Cross Document Transport of JavaScript Data
*
* Extensible Wrapper for HTML 5's DOM Storage, Microsoft's UserData,
* Session Cookies and window.name using JSON serialization
*
* Author: Mathias Schaefer <molily@mailbox.org>
* License: Public Domain
*
*/
/* Anonymous Function Wrapper to establish a local variable scope */
(function (window, document) {
/* ******************************************************************** */
/* Public Interface Name */
var publicInterfaceName = "ssw";
/* ******************************************************************** */
/* Helper Functions */
var helper = {
/*
* Iteration of objects and arrays
* Fire the callback function for each member and break if it returns a value.
* In this case, pass this return value on.
* The callback gets the member as first parameter, the index or name as second.
* In the callback, "this" points to the object or array.
*/
forEach : function (obj, func) {
if (obj.constructor == Array) {
// Array (defined order)
for (var i = 0, length = obj.length; i < length; i++) {
var result = func.call(obj, obj[i], i);
if (result != undefined) {
return result;
}
}
} else {
// Object (order not relevant)
for (var name in obj) {
if (obj.hasOwnProperty(name)) {
var result = func.call(obj, obj[name], name);
if (result != undefined) {
return result;
}
}
}
}
return null;
},
/*
* Copy all members of one object to another object
* (objects are referenced, primitives are copied)
*/
mixin : function (source, target) {
helper.forEach(source, function (value, name) {
target[name] = value;
});
return target;
},
/*
* Bind a function to an object so the "this" keyword points to the given object
*/
bind : function (func, obj) {
return function () {
return func.apply(obj, arguments);
};
},
/*
* Load an external JavaScript
*/
loadScript : function (uri) {
/* Load and evaluate the script with synchronous XMLHttpRequest.
That's really ugly, but there's no other reliable solution.
Otherwise it cannot be guaranteed that the dependancy is fully loaded
and executed by the time the public methods of this script are used. */
/* TODO: Switch to an asynchronous API */
var req = (window.XMLHttpRequest ? new XMLHttpRequest : (window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : false));
if (!req) {
return false;
}
req.open('GET', uri, false);
req.send(null);
eval(req.responseText);
}
};
/* ******************************************************************** */
/* Serializers */
var serializers = {
/* JSON Serializer */
json : {
/* URI of the JSON script */
scriptUri : "./json2.js",
init : function () {
/* Load additional script if there's no native JSON implementation */
if (!window.JSON) {
helper.loadScript(this.scriptUri);
}
},
serialize : function (object) {
if (!(window.JSON && JSON.stringify)) {
throw new Error("JSON serialization not available");
}
return JSON.stringify(object);
},
unserialize : function (string) {
if (!(window.JSON || JSON.parse)) {
throw new Error("JSON parsing not available");
}
return JSON.parse(string);
}
}
};
/* ******************************************************************** */
/* Implementation Object */
var implementation = {
/* Implementation List (an array and a hash at the same time) */
list: [],
/* Add an implementation (with possibility to mixin a template) */
add : function (obj1, obj2) {
/* Prepare implementation object, mixin template if two objects are given */
var imp = arguments.length == 1 ? obj1 : helper.mixin(obj1, obj2);
if (imp) {
/*
* Push the object into the array *and* save it as a property
* so we can retrieve it by index or name.
*/
this.list.push(imp);
this.list[imp.name] = imp;
}
},
/* Get an implementation object by index or name */
get : function (param) {
return this.list[param];
},
/* Auto-Detect available implementation */
detect : function () {
/* Iterate over implementation list, check if the implementation is available,
set the available property accordingly and make use of the first supported implementation */
var availableImp = null;
helper.forEach(this.list, function (imp) {
if (imp.isAvailable()) {
imp.available = true;
availableImp = availableImp || imp;
} else {
imp.available = false;
}
});
this.setup(availableImp);
},
/* Force an implementation (override auto-detect, but check availability) */
force : function (name) {
var imp = this.get(name);
if (!imp || !imp.available) {
imp = false;
}
return this.setup(imp);
},
/* Setup and initialize an implementation */
setup : function (imp) {
/* If the implementation is not supported, set the global object to false and break */
if (!imp) {
return window[publicInterfaceName] = false;
}
/* Call the specific init function of the implementation */
imp.init();
/* Set up the public interface object */
var publicInterface = {
/* Provide chosen implementation */
implementation : imp,
/* Provide method to force another implementation */
forceImplementation : helper.bind(this.force, this)
};
/* Provide core methods from the implementation */
helper.forEach(["get", "add", "remove", "clear"], function (methodName) {
/* Copy the bound function to the public interface */
publicInterface[methodName] = helper.bind(imp[methodName], imp);
});
/* Finally, create the global object */
return window[publicInterfaceName] = publicInterface;
}
};
/* ******************************************************************** */
/* Implementation Templates (Mixins) */
var mixins = {
/* Template for implementations which save all data in a serialized string */
serialized: {
/* Private members */
/* Use JSON as standard serializer */
serializer: serializers.json,
/* Store Object */
box: null,
/* Initialization */
init : function () {
/* Initialize serializer. */
this.serializer.init();
/* Call the specific init method */
if (this.specificInit) {
this.specificInit();
}
},
/*
* Implementation specific private methods:
* isAvailable
* read
* save
* specificInit (optional)
* specificClear (optional)
*/
/* Internal members */
readBox : function () {
/* Initial reading and unserializing if box hasn't been set up */
if (this.box) {
return;
}
var string = this.read();
this.box = string && string.charAt(0) == "{" ? this.serializer.unserialize(string) : {};
},
saveBox : function () {
var serializedString = this.serializer.serialize(this.box);
this.save(serializedString);
},
/* Public members */
get : function (param1) {
this.readBox();
return param1 != undefined ? this.box[param1] : this.box;
},
add : function (param1, value) {
this.readBox();
if (arguments.length == 1) {
helper.mixin(param1, this.box);
} else {
this.box[param1] = value;
}
this.saveBox();
},
remove : function (name) {
this.readBox();
if (name in this.box) {
delete this.box[name];
this.saveBox();
}
},
clear : function () {
this.box = {};
this.saveBox();
if (this.specificClear) {
this.specificClear();
}
}
}
};
/* ******************************************************************** */
/* Implementations */
/* -------------------------------------------------------------------- */
/* DOM Storage, using serialized template */
implementation.add(mixins.serialized, {
name: "domstorage",
/* Necessary methods */
isAvailable : function () {
return Boolean(window.sessionStorage);
},
read : function () {
var serializedString = sessionStorage.getItem(this.storeName);
return serializedString === null ? "" : serializedString.toString();
},
save : function (serializedString) {
return sessionStorage.setItem(this.storeName, serializedString);
},
/* Internal members */
storeName : publicInterfaceName,
specificInit : function () {
},
specificClear : function () {
}
});
/* -------------------------------------------------------------------- */
/* userData, using serialized template */
implementation.add(mixins.serialized, {
name : "userdata",
/* Necessary methods */
isAvailable : function () {
return Boolean(document.documentElement && document.documentElement.addBehavior);
},
read : function () {
this.element.load(this.storeName);
return this.element.getAttribute(this.storeName);
},
save : function (serializedString) {
this.element.setAttribute(this.storeName, serializedString);
this.element.save(this.storeName);
},
/* Internal members */
/* Fictional tag name of the element which gets the userData behavior */
storeName : publicInterfaceName,
specificInit : function () {
/* Create a non-existing element and append it to the root element (html) */
var el = document.createElement(this.storeName);
document.documentElement.appendChild(el);
/* Apply userData behavior */
el.addBehavior("#default#userData");
this.element = el;
},
specificClear : function () {
/* Expire at once */
this.element.expires = new Date(0).toUTCString();
}
});
/* -------------------------------------------------------------------- */
/* Cookie, using serialized template */
implementation.add(mixins.serialized, {
name : "cookie",
/* Necessary methods */
isAvailable : function () {
/* Try to set and get a cookie to test if session cookies are allowed */
var s = this.cookieName + "-test";
this.setCookie(s, s);
return this.getCookie(s) == s ? (this.deleteCookie(s), true) : false;
},
read : function () {
return this.getCookie(this.cookieName);
},
save : function (serializedString) {
if (!serializedString) {
/* break if the string is empty */
return;
}
this.setCookie(this.cookieName, serializedString);
},
/* Internal members */
cookieName : publicInterfaceName,
specificClear : function () {
this.deleteCookie(this.cookieName);
},
escapeCookie : function (value) {
/*
* Just escape semicolon and double quotes (the latter escpecially for Opera),
* which is more economic than using encodeURIComponent/decodeURIComponent.
*/
return value.replace(/%/g, "%%").replace(/;/g, "%S").replace(/"/g, '%Q');
},
unescapeCookie : function (value) {
return value.replace(/%Q/g, '"').replace(/%S/g, ";").replace(/%%/g, "%");
},
getCookie : function (name) {
var pairs = document.cookie.split(/;\s*/),
value = helper.forEach(pairs, function (str) {
if (!str) {
return;
}
var separatorPosition = str.indexOf("="),
testName = str.substring(0, separatorPosition);
if (testName == name) {
return str.substring(separatorPosition + 1);
}
});
if (!value) {
return false;
}
return this.unescapeCookie(value);
},
setCookie : function (name, value) {
var cookieString = name + "=" + this.escapeCookie(value);
if (cookieString.length > 4096) {
throw new Error("Cookie size exceeds 4096 byte limit");
}
document.cookie = cookieString;
},
deleteCookie : function (name) {
document.cookie = name + '=;expires=' + new Date(0).toUTCString();
}
});
/* -------------------------------------------------------------------- */
/* Window name, using serialized template */
implementation.add(mixins.serialized, {
name: "windowname",
/* Necessary methods */
isAvailable : function () {
return (typeof window.name != "undefined");
},
read : function () {
return window.name;
},
save : function (serializedString) {
window.name = serializedString;
}
});
/* ******************************************************************** */
/* Call auto-detect */
implementation.detect();
/*
* Delete the implementation object to free some memory. Otherwise
* it would be kept in memory due to the many closures (nested functions).
*/
implementation = null;
/* Call the anonymous function: */
})(window, document);