HTML5 Local Storage

HTML5 provides four different types of Storage of data on a local client's machine. They are

  1. Local Storage.
  2. Web SQL Storage.
  3. Session Storage
  4. Indexed DB

This article describes the Local Storage and Web SQL Storage with sample code.

The source code for the samples described in this article can be found here: https://github.com/gomobile/sample-html5-local-storage and here: https://github.com/gomobile/sample-html5-web-sql-storage.

Local Storage and Web SQL Storage are commonly called Web storage. This is the common programming interface for Web pages. These are an improvement to the cookies. They are limited in size and varies from 5 MB to 10 MB. They don't send the data to the server but store the data on the local client machines. Local Storage is persistent storage and Session storage is transient.

Technical Information

Local Storage Part 1: Check if Local storage is supported by the browser and get the object if it is supported. 

var db = getLocalStorage();

function getLocalStorage() {
    try {
        if(window.localStorage ) return window.localStorage;            
    }
    catch (e)
    {
        return undefined;
    }
}

Local Storage Part 2: Set the Key value pair using the SetItem() function. 

We need to get the key and values from the text editor and using the db.setItem() function we set the values in the local storage. getlocal() is the function that retrieves the values from the storage and displays it every time the page loads. getLocal() function is described in the next section.

function setlocal() 
{            
    db.setItem(document.getElementById("txtKey").value,
          document.getElementById("txtValue").value);
    getlocal();           
 }

Local Storage Part 3: Retrieve the Key, value pair values using the getItem() function.

We need to get the key and values from the text editor and using the db.setItem() function we set the values in the local storage. getlocal() is the function that retrieves the values from the stroage and displays it every time the page loads. getLocal() function is described in the next section.

function getlocal()
 {            
    var res = document.getElementById("r");
    var pairs;            
    var i=0;
    res.innerHTML  = "";
    for (i=0; i<=db.length-1; i++) {
    key = db.key(i);             
    res.innerHTML += "<div>"+ "key: "+ key +" value: "+db.getItem(key)+"</div>";;
   }  
}

Web SQL Storage Part 1: Getting Started

Web SQL storage is an interface to a SQL relational database.Web SQL Storage uses SQLite3 as the database engine. Supported in Safari, Chrome and opera browsers. The first thing we need to do is to check if the browser supports Web SQL storage. Below is the function that checks for that and gets the storage object.

function getopenDb() { 
    try {
        if (window.openDatabase) {                    
            return window.openDatabase;                    
        } else {
            alert('No HTML5 support');
            return undefined;
        }
    }
    catch (e) {
        alert(e);
        return undefined;
    }            
}

Web SQL Storage Part 2: Create the table.

Once we get the storage object we need to create a table. The below function creates a table on a condition that if that if the table does not exist. We call the get getopenDb() function that is detailed above and if Web SQL is supported, we call the db.transaction method to initiate the Create table transaction. Then we call the executeSql() function to execute a Create table query. Below is the function

function createTable() {
    var openDB = getopenDb();
    if(!openDB)
    {                
        return;               
    }
    else
    {
        db = openDB('mydatabase', '1.0', 'my db', 2*1024*1024);
        db.transaction(function (t) { 
        t.executeSql('CREATE TABLE IF NOT EXISTS 
            myTable(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL DEFAULT "JohnDoe", age INT NOT NULL);', [], null, null);               
        
    });
    selRows();
    return db;
    }            
}

Web SQL Storage Part 3: Get the storage object on Initialization.

In the starting of the scripts section we call the below code. "db" is the object that we are going to execute the commands

var db = createTable();

Web SQL Storage Part 4: Inserting into the Web SQL Storage.

We need to call the db.transaction method to initiate the "Insert" transaction. and then we call the executeSql() function to execute the Insert into table query. Below is the function

function insert() {
    if(!db)
    {                
        return;                
    }
    var name = document.getElementById("name").value;
    var age = document.getElementById("age").value;

    db.transaction(function (t) { 
        t.executeSql("INSERT INTO myTable('name','age') 
           values('" + name + "'," + age + ");", [], null, null);
        alert("Row Inserted!");
        selRows();
    });
}

Web SQL Storage Part 5: Selecting from the table.

This is similar to the above. The below function will select from the database and display the results.

function selRows() {
    
    var q = "select * from myTable";
    
    db.transaction(function (t) {
        t.executeSql(q, null, function (t, data) {
            var html = "<table><tr><td>ID</td><td>Name</td><td>Age</td></tr>";
            for (var i = 0; i < data.rows.length; i++) {
                  html += "<tr><td>" + 
                  data.rows.item(i).id + "</td><td>" +
                  data.rows.item(i).name + "</td><td>" +
                  data.rows.item(i).age + "</td></tr>";
            }
            html += "</table>";
            var el = document.getElementById("main");
            el.innerHTML = html;
        });
    });
}

The Local Storage and the Web SQL Storage applications are tested on a Google Android* 4.0 smartphone, an Android 2.x tablet, and an Apple iPad* tablet running Apple iOS* 5.1

For more complete information about compiler optimizations, see our Optimization Notice.