Storing Objects in HTML5 Local Storage

Tweet about this on TwitterShare on LinkedIn0Share on Google+0Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page

Storing Objects in HTML5 Local Storage

W3schools

With HTML5, web pages can store data locally within the user’s browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website’s performance.
The data is stored in name/value pairs, and a web page can only access data stored by itself.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

So, what all can you store in the Local storage?? Actually, A complete circus! (pun intended). You can store strings, numbers, objects, complex objects arrays etc. Lets see the syntax to store & fetch stuff from your browser’s storage.

PS: Do not save sensitive data like passwords, SSN or account nos, etc..

First, lets check If local storage is supported.

You can check the local storage support here. Programmatically,

The Get & Set methods

Strings

Numbers

Objects

The above way of storing a object will not really give the object back. This is because, when you evaluate the object  me, it will return the string “[object Object]”. Which eventually ends up saved inside the Local storage. Below is the solution

Sweet right? But, JSON is not supported in all browser, you can check here. You can also use jQuery’s parse JSON method if you are already using jQuery. Else you can use the same logic jQuery is using to parse the JSON. Excerpt from jquery-1.11.0.js

This post from SO gives a solution or rather the code for JSON parse() & stringify(). You can copy paste the below code into your js file. Check if Window.JSON is present. if not, load it up.

Polyfill:

Then you can use   JSON.parse(object);   JSON.stringfy(string);.

Now how do we store complex objects?

Simple right! Do try and make use of local storage for its advantages over cookies.


Thanks for reading! Do comment.
@arvindr21

 

Tweet about this on TwitterShare on LinkedIn0Share on Google+0Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page
  • Peter Bruins

    Thanks for the great article! Saved me some time!

  • SB

    Can you store arrays in the local storage using stringify and parse? I am trying a FIFO array and here is my code – is this the right approach? $storage is a factory item for me implemented as shown from ionic tutorial:

    angular.module(‘ionic.utils’, [])
    .factory(‘$storage’, [‘$window’, function($window) {
    return {
    set: function(key, value) {
    $window.localStorage[key] = value;
    },
    get: function(key, defaultValue) {
    return $window.localStorage[key] || defaultValue;
    },
    setObject: function(key, value) {
    $window.localStorage[key] = JSON.stringify(value);
    },
    getObject: function(key) {
    return JSON.parse($window.localStorage[key] || ‘{}’);
    },
    clear: function() {
    $window.localStorage.clear();
    }
    }
    }]);

    JS code:

    //Retrieve data from localstorage
    var Data = $storage.getObject(“Data”); //returns parsed data
    var Count = $storage.get(“Count”);

    if (Count < lengthHistory){
    Count++;
    } else {
    Data.shift();
    }
    Data.push($scope.meas);

    //store the data back
    $storage.setObject(Data);

  • Sarah Geeleher Mullen

    Thanks for the tutorial, it got me quite far in what I was trying to achieve. My one problem though is accessing the string afterwards. I can alert the variable object fine but when it comes to outputting the data into a div it does not work.

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Can you create a jsfiddle or paste your sample code here?

      • Sarah M

        Hi thanks for the quick reply!
        I am working on a PhoneGap project.
        I am trying to store the values childName and childLevel under the same key. It is being stored successfully, and will alert the correct values. My problem is actually getting the alerted values to print into a div called output.

        function personalSettings() {

        parent.children = {};
        var childName = $(‘[name=”username”]’).val(); //input from textfield
        var childLevel = $(‘input[name=”level”]:checked’).val(); //input from radio buttons

        parent.children = {name:childName, level:childLevel};
        window.localStorage.setItem(“children”,JSON.stringify(parent.children));
        console.log(window.localStorage.getItem(“children”));

        parent.children = JSON.parse(window.localStorage.getItem(“children”)); //js obj
        alert(parent.children.name + ” ” + parent.children.level); //this alerts values typed in
        $(‘#output’).html(window.localStorage.getItem(“parent.children.name”));

        $.mobile.changePage( “#titlePage”, { reverse: false, transition: “slide” } );

        return false;//not going to server, going to script
        }

        • http://thejackalofjavascript.com/ Arvind Ravulavaru

          I think the below line

          should be

          because you already have gathered that value using

          Let me know if this works.

          Thanks.

          • Sarah M

            Yes that worked, thank you so much. I am new to this and I was tearing my hair out!

  • livtoplay

    thanks for the tutorial . really good work.

  • NabeelTahir

    Can we store javascript object directly into local Storage????????

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      No you cannot. You need to stringify it while saving and parse it while retrieving. You can see the examples above.

  • evaluations in

    nice tutorial

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks @evaluationsin:disqus