Last Updated: February 25, 2016
·
3.433K
· steveniseki

Store JavaScript objects in HTML5 local storage

It is easy enough to pollyfill the localStorage object to store and retrieve objects rather than just strings.

if ( !Storage.prototype.setObject ) {
    Storage.prototype.setObject = function(key, value) {
        this.setItem(key, JSON.stringify(value));
    }
}

if ( !Storage.prototype.getObject ) {
    Storage.prototype.getObject = function(key) {
        var value = this.getItem(key);
        return value && JSON.parse(value);
    }
}

Now we can simply get and set objects from localStorage.

var apps = {
        appName : 'Links app',
        settings : {'type' : 'link'}
};  

localStorage.setObject('apps', apps );

var ourApps = localStorage.getObject('apps');

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside