HTML5 Local Storage

Table of Contents

Encapsulator Compatibility for this Article
Feature Supported?
JavaScript yes
CSS yes
Local Storage yes
Web SQL Storage yes

Introduction

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

  1. Local Storage.
  2. Web SQL Storage.

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

Technical Information

1. Local Storage.

Part 1: Check if Local storage is supported by the browser and get the object if supported.
var db = getLocalStorage() || alert("Local Storage Not supported in this browser");

function getLocalStorage() {
    try {
        if(window.localStorage ) return window.localStorage;            
    }
    catch (e)
    {
        return undefined;
    }
}
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 stroage and displays it everytime the page loads. getLocal() function is described in the next section.



function setlocal() 
{            
    db.setItem(document.getElementById("txtKey").value, document.getElementById("txtValue").value);
    getlocal();           
 }
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 everytime 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>";;
   }  
}
Below is the complete source code for Local Storage.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Local Storage Example</title>
    <script language="javascript" type="text/javascript">
    
     var db = getLocalStorage() || alert("Local Storage Not supported in this browser");
    
        function getLocalStorage() {
            try {
                if(window.localStorage ) return window.localStorage;            
            }
            catch (e)
            {
                return undefined;
            }
        }
        function setlocal() {
            
            db.setItem(document.getElementById("txtKey").value, document.getElementById("txtValue").value);
            getlocal();           
        }
        
        function ClearAll() {
            
            db.clear();
            getlocal();           
        }
        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>";;
           }        
          
        }       
        
    </script>
    <style>
        *{font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;}
        fieldset{border-radius: 5px;padding:20px;}        
        .btn {
            border-radius: 5px;
            border:1px solid #000;
            background-color:#cccccc;
            padding:5px;
        }
        table{
            border: 1px; solid; #000;
        }
        
    </style>
</head>
<body onload="getlocal()">
<fieldset>
    <legend>Local Storage</legend>
    <input type="text" id="txtKey" /> : <input type="text" id="txtValue" /> <a id="setbtn" class="btn" href="javascript:void(0);"  onclick="setlocal();">Set!</a> <a id="clear" href="javascript:void(0);" class="btn" onclick="ClearAll();">Clear!</a>
    <div id="r"></div>    
</fieldset>
</body>
</html>
2: Web SQL Storage.

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;
    }            
}
Part 2: Creating 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', 10*1024*1024);
        db.transaction(function (t) { //t = transaction
        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;
    }            
}
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();
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 = transaction
        t.executeSql("INSERT INTO myTable('name','age') values('" + name + "'," + age + ");", [], null, null);
        alert("Row Inserted!");
        selRows();
    });
}
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 = transaction
        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;
        });
    });
}
Below is the complete source code for the Web SQL Storage.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Web SQL Storage</title>
    <script language="javascript" type="text/javascript">   
        
        var db = createTable();
        
        function getopenDb() { 
            try {
                if (window.openDatabase) {                    
                    return window.openDatabase;                    
                } else {
                    alert('No HTML5 support');
                    return undefined;
                }
            }
            catch (e) {
                alert(e);
                return undefined;
            }            
        }
        function createTable() {
            var openDB = getopenDb();
            if(!openDB)
            {                
                return;               
            }
            else
            {
                db = openDB('mydatabase', '1.0', 'my db', 10*1024*1024);
                db.transaction(function (t) { //t = transaction
                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;
            }            
        }
        function insert() {
            if(!db)
            {                
                return;                
            }
            var name = document.getElementById("name").value;
            var age = document.getElementById("age").value;
        
            db.transaction(function (t) { //t = transaction
                t.executeSql("INSERT INTO myTable('name','age') values('" + name + "'," + age + ");", [], null, null);
                alert("Row Inserted!");
                selRows();
            });
        }
        function selRows() {
            
            var q = "select * from myTable";
            
            db.transaction(function (t) { //t = transaction
                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;
                });
            });
        }
        
        function clearDB() {
            if(!db)
            {                
                return;                
            }
            if(confirm('Clear the entire table?')) {
                db.transaction(function(t) {
                    t.executeSql('DELETE FROM myTable');
                });
                selRows();
            }
        }
        
    </script>
    <style>
        *{font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;}
        fieldset{border-radius: 5px;padding:20px;}        
        .btn {
            border-radius: 5px;
            border:1px solid #000;
            background-color:#cccccc;
            padding:5px;
        }
        table{
            border: 1px; solid; #000;
        }
        
    </style>
</head>
<body>
<fieldset>
<legend>Web SQL Storage</legend>
<h4>Insert Rows</h4>
Name: <input type="text" id="name" /> Age: <input type="text" id="age" /><a href="javascript:void(0);" class="btn" onclick="insert();">Insert</a>
<a href="javascript:void(0);" class="btn" onclick="clearDB();">Clear</a>
</fieldset>
<div id="main"></div>
</body>
</html>

More resources

This is a section to refer to other great articles, tutorials, reference documents, etc ... Some good places to look for more information might include:

  1. Mozilla Developers Network

  2. W3C HTML 5 Reference

  3. Dive into HTML5

0