HTML5 local Storage and session Storage tutorial

How to read and write to local storage

Before HTML5 you have use cookies to store data on the client machine. Now with HTML5 you have ability to store data by domain name in name and value pairs. This new Web storage is currently available on most browsers. Also Web Storage is more secure and faster access than cookies. In this tutorial we are going to cover how to store simple data and complex data in Web Storage.

Web storage has two objects localStorage and sessionStorage. As you can see from the name that the sessionStorage keeps the data as long as you maintain the session. So closing the browser window will clean the storage. However the localStorage will keep the data for the given domain name as long as you don't clear it. The current storage limit is around 5MB per domain in most browsers. With localStorage you can save user preferences and other application settings on the client machine.

HTML5 local storage and session storage tutorial
HTML5 local storage and session storage tutorial

How to check if local Storage is supported by the browser

    if (typeof(Storage) == "undefined" ) {
            alert("Your browser does not support HTML5 localStorage. Try upgrading.");
    } 
    else {
        console.log("Both localStorage and sessionStorage support is there.");
    }

How to store data in local storage

Method: localStorage.setItem(key,value)
Local storage data is saved in name and value pairs. If the key already exists the value with just
get updated otherwise the name and value pair get added to the local storage.

Example:
    var myName = document.getElementById("name");
    var age = document.getElementById("age");
   
    try {
        localStorage.setItem("name", myName.value);
        localStorage.setItem("age", age.value);
        myName.value = "";
        age.value = "";
    } 
    catch (e) {
        if (e == QUOTA_EXCEEDED_ERR) {
            console.log("Error: Local Storage limit exceeds.");
        }
        else {
            console.log("Error: Saving to local storage.");
        }
    } 

As you can see we have put our localStorage.setItem(key,value) in a try and catch to check if the storage limit exceeded or not and for any other exceptions.
  

How to retrieve the value from the local storage

Method: localStorage.getItem(key)
If the key was not set before you tried to retrieve it will not throw an exception, it will just return null.

Example:
    var myName = document.getElementById("name");
    var age = document.getElementById("age");
    myName.value = localStorage.getItem("name");
    age.value = localStorage.getItem("age"); 

How to remove data from local storage  

Method: localStorage.removeItem(key)
It will not throw an exception if you try to remove the key before it was set.

Example:
    localStorage.removeItem("name");
    localStorage.removeItem("age");

How to wipe clean your local Storage

Method: localStorage.clear()

How to store JavaScript data objects to local storage

Method: localStorage.setItem(key, JSON.stringify(yourObject))
Well the local storage is only limited to name and value pairs. So you have to
stringify your object before storing it. This will work JSON objects, JavaScript Arrays etc.

Example:
    var myName = document.getElementById("name");
    var age = document.getElementById("age");
    var personObject = new Object();
    personObject.name = myName.value;
    personObject.age = age.value;
    localStorage.setItem("person", JSON.stringify(personObject));

How to restore the JSON objects from local Storage

Method: JSON.parse(localStorage.getItem(key)
Retrieve the object from the local storage then use JSON parsing.

Example:
    var myName = document.getElementById("name");
    var age = document.getElementById("age");
    var personObject = JSON.parse(localStorage.getItem("person"));
    myName.value = personObject.name;
    age.value = personObject.age;

How to save an array in local storage

Example:
    var myArrayObject = [];
   
    var personObject1 = new Object();
    personObject1.name = "Array1";
    personObject1.age = 23;
    myArrayObject.push(personObject1);
   
    var personObject2 = new Object();
    personObject2.name = "Array2";
    personObject2.age = 24;
    myArrayObject.push(personObject2);
   
    var personObject3 = new Object();
    personObject3.name = "Array3";
    personObject3.age = 25;
    myArrayObject.push(personObject3);
   
    localStorage.setItem("persons", JSON.stringify(myArrayObject));

How to read an array from local storage

Example:
    var myArrayObject = JSON.parse(localStorage.getItem("persons"));
    for (var i=0; i<myArrayObject.length; i++){
        var personObject = myArrayObject[i];
        console.log("Name: " + personObject.name, "Age: " + personObject.age);
    }    


HTML source code for the above example - index.html

<!DOCTYPE html>
<html>
<head>
    <title>Getting Started with HTML5 local storage</title>
    <script type="text/javascript" src="app.js"></script>
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
    <tr>
        <td>Name:</td>
        <td><input type="text" id="name"></td>
    </tr>
    <tr>
        <td>Age:</td>
        <td><input type="text" id="age">
    </tr>
</table>
<table>   
    <tr>
        <td>&nbsp;</td>
        <td>
            <input type="button" id="add" value="Add to Storage" onclick="Javascript:save()">
        </td>
        <td>&nbsp;</td>
        <td>
            <input type="button" id="get" value="Get from Storage" onclick="Javascript:get()">
        </td>
        <td>&nbsp;</td>
        <td>
            <input type="button" id="del" value="Remove from Storage" onclick="Javascript:remove()">
        </td>
        <td>&nbsp;</td>
        <td>
            <input type="button" id="clear" value="Clear Local Storage" onclick="Javascript:clearStorage()">
        </td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>
            <input type="button" id="saveC" value="Save complex data" onclick="Javascript:saveComplexData()">
        </td>
        <td>&nbsp;</td>
        <td>
            <input type="button" id="restoreC" value="Restore complex data" onclick="Javascript:restoreComplexData()">
        </td>
        <td>&nbsp;</td>
        <td>
            <input type="button" id="sArray" value="Save Array data" onclick="Javascript:saveArrayData()">
        </td>
        <td>&nbsp;</td>
        <td>
            <input type="button" id="rArray" value="Restore Array data" onclick="Javascript:restoreArrayData()">
        </td>
    </tr>
</table>
</div>
</body>
</html>

JavaScript source code for local Storage example - app.js

function save() {
         
    var myName = document.getElementById("name");
    var age = document.getElementById("age");
   
    try {
        localStorage.setItem("name", myName.value);
        localStorage.setItem("age", age.value);
        myName.value = "";
        age.value = "";
    } 
    catch (e) {
        if (e == QUOTA_EXCEEDED_ERR) {
            console.log("Error: Local Storage limit exceeds.");
        }
        else {
            console.log("Error: Saving to local storage.");
        }
    } 
}

function get() {
    console.log("Getting your data from local storage.");
    var myName = document.getElementById("name");
    var age = document.getElementById("age");
    myName.value = localStorage.getItem("name");
    age.value = localStorage.getItem("age");
   
}

function remove() {
    console.log("Removing data from local storage.");
    localStorage.removeItem("name");
    localStorage.removeItem("age");
   
}

function clearStorage() {
    console.log("Clearing local storage."); 
    localStorage.clear();
   
}

function saveComplexData() {
    console.log("Saving complex data to local storage.");
    var myName = document.getElementById("name");
    var age = document.getElementById("age");
    var personObject = new Object();
    personObject.name = myName.value;
    personObject.age = age.value;
    localStorage.setItem("person", JSON.stringify(personObject));
   
}

function restoreComplexData() {
    console.log("Restoring complex data from local storage.");
    var myName = document.getElementById("name");
    var age = document.getElementById("age");
    var personObject = JSON.parse(localStorage.getItem("person"));
    myName.value = personObject.name;
    age.value = personObject.age;
}

function saveArrayData() {
    console.log("Saving array data to local storage.");
    var myArrayObject = [];
   
    var personObject1 = new Object();
    personObject1.name = "Array1";
    personObject1.age = 23;
    myArrayObject.push(personObject1);
   
    var personObject2 = new Object();
    personObject2.name = "Array2";
    personObject2.age = 24;
    myArrayObject.push(personObject2);
   
    var personObject3 = new Object();
    personObject3.name = "Array3";
    personObject3.age = 25;
    myArrayObject.push(personObject3);
   
    localStorage.setItem("persons", JSON.stringify(myArrayObject));
   
}

function restoreArrayData() {
    console.log("Restoring array data from local storage.");
   
    var myArrayObject = JSON.parse(localStorage.getItem("persons"));
    for (var i=0; i<myArrayObject.length; i++){
        var personObject = myArrayObject[i];
        console.log("Name: " + personObject.name, "Age: " + personObject.age);
    }
   
}


function load() {
   
    console.log("Page load finished");
    if (typeof(Storage) == "undefined" ) {
            alert("Your browser does not support HTML5 localStorage. Try upgrading.");
    } 
    else {
        console.log("Both localStorage and sessionStorage support is there.");
    }
}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.