Monday, August 29, 2011

Persistent local storage in a PhoneGap app using HTML5

I was trying to save a few bits of data across webkit browser invocations in a PhoneGap app.  My first approach was to save the data in a file, using PhoneGap's File API.  That got tedious fast.  Lucky for me, PhoneGap contributor Bryce suggested that I make use of a simple, new feature in HTML5: persistent local storage.

Google returned a good reference on the first search:  http://diveintohtml5.org/storage.html

I wrote two sandbox programs with three buttons to demonstrate how to save, fetch, and delete.  The first program handles a single string.

String demo


<!DOCTYPE HTML>
<html>
    <head>
        <title>HTML5 Persistent String</title>
        
        <script type="text/javascript" charset="utf-8">
        
            //---------------------------------------
            // Button handlers
            //---------------------------------------
            function setit() {
                var stringValue = "Hello World!";
                localStorage.setItem("string_key", stringValue);
                document.getElementById("stringResponseText").innerHTML = 
                    "Set string value: " + stringValue;
            }
            function nullit() {
                localStorage.setItem("string_key", null);
                document.getElementById("stringResponseText").innerHTML = 
                    "Set string value to null.";
            }
            function getit() {
                var stringValue = localStorage.getItem("string_key"); 
                document.getElementById("stringResponseText").innerHTML = 
                    "Got string value: " + stringValue; 
            }
        </script>
    </head>
    <body bgcolor="lightgreen">
        <h2>HTML5 Persistent String</h2>
        <input type="button" value="set" onclick="setit()" />
        <input type="button" value="get" onclick="getit()" />
        <input type="button" value="null" onclick="nullit()" />
        <p>
        <p id="stringResponseText"> </p>        
    </body>
</html>



Object demo

The second program follows the same pattern, but with a user-defined javascript object.  The secret here is to use JSON.stringify to convert your object into a 'flat' string for saving, and JSON.parse() to reconstitute the object after it is read.


<!DOCTYPE HTML>
<html>
    <head>
        <title>HTML5 Persistent Object</title>
        
        <script type="text/javascript" charset="utf-8">
        
            //---------------------------------------
            // Object definition and accessor
            //---------------------------------------
            function myObject(var1, var2, var3) {
                this.one = var1;
                this.two = var2;
                this.three = var3;
                this.toString = toString;
            }
            function toString() {
                return "one=" + this.one +
                       " two=" + this.two + 
                       " three=" + this.three;
            }
            
            //---------------------------------------
            // Button handlers.            
            //---------------------------------------
            function setIt() {
                var testObject = new myObject( "bird", "cat", "dog" );
                localStorage.setItem("object_key", JSON.stringify(testObject));
                document.getElementById("objectResponseText").innerHTML = 
                    "Set object value: " + testObject.toString();
            }
            function nullIt() {
                localStorage.setItem("object_key", null);
                document.getElementById("objectResponseText").innerHTML = 
                    "Set object value to null.";             
            }
            function getIt() {
                var stringifiedObject = localStorage.getItem("object_key");
                var reconstitutedObject = JSON.parse(stringifiedObject);
                if (reconstitutedObject) {
                    reconstitutedObject.toString = toString;
                    document.getElementById("objectResponseText").innerHTML = 
                        "Got object value: " + reconstitutedObject.toString(); 
                }
                else {
                    document.getElementById("objectResponseText").innerHTML = 
                        "Object value not found.";
                }
            }
        </script>
    </head>
    <body bgcolor="lightblue">
        <h1>HTML5 Persistent Object</h1>
        <h3>Object</h3>
        <input type="button" value="set" onclick="setIt()" />
        <input type="button" value="get" onclick="getIt()" />
        <input type="button" value="null" onclick="nullIt()" />
        <p>
        <p id="objectResponseText"> </p>        
    </body>
</html>




Testing

These sandbox programs can be browsed directly with a browser which supports HTML5, such as Chrome or Safari.

They can also be bundled into a PhoneGap app (via index.html), where they will work well installed on a mobile device.

Hope this is useful!

2 comments:

  1. Thanks for simple and concise explanation!
    Saved me an hour!

    ReplyDelete
  2. is it possible to save a JS-file into localStorage or filesystem and use it?

    ReplyDelete

Note: Only a member of this blog may post a comment.