The localStorage
and sessionStorage
can only handle strings. You can extend the default storage-objects to handle arrays and objects. Just include this script and use the new methods:
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
}
Use localStorage.setObj(key, value)
to save an array or object and localStorage.getObj(key)
to retrieve it. The same methods work with the sessionStorage
object.
If you just use the new methods to access the storage, every value will be converted to a JSON-string before saving and parsed before it is returned by the getter.
Source: http://www.acetous.de/p/152