localStorage is a feature of HTML5’s Web Storage. You can store or retrieve as the followings:
localStorage['key'] = value; value = localStorage['key']; delete localStorage['key']; localStorage.setItem('key', value); value = localStorage.getItem('key'); localStorage.removeItem('key'); localStorage.key = value; value = localStorage.key; delete localStorage.key;
You can list:
for (key in localStorage) console.log(key, localStorage[key]);
You can clean up at once:
localStorage.clear();
You can put every thing in but you might not get what you put in, because
The setItem(key, value) method must first create a structured clone of the given value. If this raises an exception, then the exception must be thrown and the list associated with the object is left unchanged. If constructing the structured clone would involve constructing a new ImageData object, then throw a NOT_SUPPORTED_ERR exception instead.
For this structured clone, it’s actually the result by calling object.toString(), from my observation. localStorage stores only String values. This would cause some inconvenient coding issue. For example, you want to store a Boolean value. You would do
localStorage.foobar_enabled = false; console.log(typeof localStorage.foobar_enabled); // prints string
You will have to retrieve the value with Boolean in this way:
// Boolean(localStorage.foobar_enabled) -> true, wrong value = localStorage.foobar_enabled == 'true';
Or you can do the followings, convert Boolean to Number first:
localStorage.foobar_enabled = Number(false); false_value = Boolean(localStorage.foobar_enabled);
The methods above are too troublesome. An answer on Stack Overflow gives a nice solution:
Storage.prototype.setObject = function(key, value) { this.setItem(key, JSON.stringify(value)); } Storage.prototype.getObject = function(key) { return JSON.parse(this.getItem(key)); }
Where JSON is defined in ECMAScript edition 5.
Now you can store and retrieve anything in JSON format (remember! Only String, Number, Array, Boolean, null, and JSON) without any problems. If it’s a Date, you need to use Date to parse.
How about function (You shouldn’t be needing this)?
localStorage.func = func.toString(); eval('func = ' + localStorage.func);
And window or document? You are crazy.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.