forked from wojodesign/local-storage-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
91 lines (78 loc) · 2.26 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
/*
Copyright (c) 2011 Wojo Design
Dual licensed under the MIT or GPL licenses.
*/
(function(){
var window = this;
// check to see if we have localStorage or not
if( !window.localStorage ){
// globalStorage
// non-standard: Firefox 2+
// https://developer.mozilla.org/en/dom/storage#globalStorage
if ( window.globalStorage ) {
// try/catch for file protocol in Firefox
try {
window.localStorage = window.globalStorage;
} catch( e ) {}
return;
}
// userData
// non-standard: IE 5+
// http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx
var div = document.createElement( "div" ),
attrKey = "localStorage";
div.style.display = "none";
document.getElementsByTagName( "head" )[ 0 ].appendChild( div );
if ( div.addBehavior ) {
div.addBehavior( "#default#userdata" );
var localStorage = window["localStorage"] = {
"length":0,
"setItem":function( key , value ){
div.load( attrKey );
key = cleanKey(key );
if( !div.getAttribute( key ) ){
this.length++;
}
div.setAttribute( key , value );
div.save( attrKey );
},
"getItem":function( key ){
div.load( attrKey );
key = cleanKey(key );
return div.getAttribute( key );
},
"removeItem":function( key ){
div.load( attrKey );
key = cleanKey(key );
div.removeAttribute( key );
div.save( attrKey );
this.length--;
if( this.length < 0){
this.length=0;
}
},
"clear":function(){
div.load( attrKey );
var i = 0;
while ( attr = div.XMLDocument.documentElement.attributes[ i++ ] ) {
div.removeAttribute( attr.name );
}
div.save( attrKey );
this.length=0;
},
"key":function( key ){
div.load( attrKey );
return div.XMLDocument.documentElement.attributes[ key ];
}
},
// convert invalid characters to dashes
// http://www.w3.org/TR/REC-xml/#NT-Name
// simplified to assume the starting character is valid
cleanKey = function( key ){
return key.replace( /[^-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u37f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/g, "-" );
};
div.load( attrKey );
localStorage["length"] = div.XMLDocument.documentElement.attributes.length;
}
}
})();