Set and get objects from/to LocalStorage

Recently, I use localStorage a lot. The HTML5 Storage API is supported in all major browsers, as well as JSON’s parse and stringify  methods. With this in mind, it is actually quite easy to save, edit and get javascript objects from user’s machines.

Here is the snippet I use to save objects to localStorage:

function saveToStorage(_name, _obj) {
    //console.log("saved to storage", _name, _obj);
    localStorage.setItem(_name, JSON.stringify(_obj));
}

Just pass a name, and a javascript object. Later, we can get the object:

function getFromStorage(_name) {
    var storageData = localStorage.getItem(_name);
    var storageObj = JSON.parse(storageData);

    if (!storageObj) {
        storageObj = {};
        saveToStorage(_name, storageObj);
    }
    return storageObj;
}

Just pass a name of the object you want to get. If such a object doesn’t exist, the function will return new, empty javascript object.

Leave a Reply