Using the Storage API



JavaScript APIs have provided some new powerful functionality, such as the ability to store more data locally and make that data available to the webpage through the Web Storage API.

Web Storage is a new API for storing webpage data locally. Two forms of Web Storage exist:

  1. local storage
  2. session storage

Web Storage is implemented as name value pairs and stored as strings. Any data that you can put into a string format can be stored in Web Storage.

The Table below lists the API methods and their usage:

Method Description
setItem Adds a key/value pair into storage. If no item with the specified key exists, the item is added; if that key does exist, its value is updated.
getItem Retrieves data from storage based on a specified key value or index.
clear Clears all storage that has been saved. Use this method to clear out the storage as needed.
key Retrieves the key at a specified index. You can use the resultant key to pass as a parameter to one of the other methods that accepts a key.
removeItem Removes the specified key/value pair from storage.

In addition to the methods described in Table , the storage objects expose a length property which returns the number of key/value pairs in storage.

Using the Local Storage API

Local storage is persistent; data stored in local storage is available to the webpage even if the user closes the browser completely and then reopens it to your site.

The Web Storage API is available as a global object. To access local storage, use the localStorage object. If you close the browser and then reopen your page, the items are still available in local storage. Availability of local storage is limited, and the storage available isn’t consistent across browsers.

The code below gives a complete solution when using the local storage:

<body>
<h1>LOCAL STORAGE</h1>
<section>
    Key:<input type="text" id="toStorageKey" /><br />
    Value:<input type="text" id="toStorageValue" /><br />
</section>
<section>
    <button type="button" id="btnAdd">Add To Storage</button>
    <button type="button" id="btnRemove">Remove from Storage</button>
    <button type="button" id="btnClear">Clear Storage</button>
</section>
<div id="storage">
    <p>Current Storage Contents</p>
</div>
    <!-- IMPLEMENTING LOCAL STORAGE -->
<script type="text/javascript">
    window.onload = function () {
        LoadFromStorage();
        var customer = new Object();
        LoadFromStorage();
        document.getElementById("btnAdd").onclick = function () {
            localStorage.setItem(document.getElementById("toStorageKey").value,
            document.getElementById("toStorageValue").value);
            LoadFromStorage();
        }
        document.getElementById("btnRemove").onclick = function () {
            localStorage.removeItem(document.getElementById("toStorageKey").value);
            LoadFromStorage();
        }
        document.getElementById("btnClear").onclick = function () {
            localStorage.clear();
            LoadFromStorage();
        }
        function LoadFromStorage() {
            var storageDiv = document.getElementById("storage");
            var tbl = document.createElement("table");
            tbl.id = "storageTable";
            if (localStorage.length > 0) {
                for (var i = 0; i < localStorage.length; i++) {
                    var row = document.createElement("tr");
                    var key = document.createElement("td");
                    var val = document.createElement("td");
                    key.innerText = localStorage.key(i);
                    val.innerText = localStorage.getItem(key.innerText);
                    row.appendChild(key);
                    row.appendChild(val);
                    tbl.appendChild(row);
                }
            }
            else {
                var row = document.createElement("tr");
                var col = document.createElement("td");
                col.innerText = "No data in local storage.";
                row.appendChild(col);
                tbl.appendChild(row);
            }
            if (document.getElementById("storageTable")) {
                document.getElementById("storageTable").replaceNode(tbl);
            }
            else {
                storageDiv.appendChild(tbl);
            }
        }
    }
    </script>
</body>

Using the Session Storage API

Session storage is available only for the duration of the current session, so if the user closes the browser, session storage is automatically cleaned up and is no longer available. To access session storage, use the sessionStorage object.

The code below gives a complete solution when using session storage:

<body>
<h1>LOCAL STORAGE</h1>
<section>
    Key:<input type="text" id="toStorageKey" /><br />
    Value:<input type="text" id="toStorageValue" /><br />
</section>
<section>
    <button type="button" id="btnAdd">Add To Storage</button>
    <button type="button" id="btnRemove">Remove from Storage</button>
    <button type="button" id="btnClear">Clear Storage</button>
</section>
<div id="storage">
    <p>Current Storage Contents</p>
</div>
    <!-- IMPLEMENTING SESSION STORAGE -->
<script type="text/javascript">
    window.onload = function () {
        LoadFromStorage();
        var customer = new Object();
        LoadFromStorage();
        document.getElementById("btnAdd").onclick = function () {
            sessionStorage.setItem(document.getElementById("toStorageKey").value,
            document.getElementById("toStorageValue").value);
            LoadFromStorage();
        }
        document.getElementById("btnRemove").onclick = function () {
            sessionStorage.removeItem(document.getElementById("toStorageKey").value);
            LoadFromStorage();
        }
        document.getElementById("btnClear").onclick = function () {
            sessionStorage.clear();
            LoadFromStorage();
        }
        function LoadFromStorage() {
            var storageDiv = document.getElementById("storage");
            var tbl = document.createElement("table");
            tbl.id = "storageTable";
            if (sessionStorage.length > 0) {
                for (var i = 0; i < sessionStorage.length; i++) {
                    var row = document.createElement("tr");
                    var key = document.createElement("td");
                    var val = document.createElement("td");
                    key.innerText = sessionStorage.key(i);
                    val.innerText = sessionStorage.getItem(key.innerText);
                    row.appendChild(key);
                    row.appendChild(val);
                    tbl.appendChild(row);
                }
            }
            else {
                var row = document.createElement("tr");
                var col = document.createElement("td");
                col.innerText = "No data in local storage.";
                row.appendChild(col);
                tbl.appendChild(row);
            }
            if (document.getElementById("storageTable")) {
                document.getElementById("storageTable").replaceNode(tbl);
            }
            else {
                storageDiv.appendChild(tbl);
            }
        }
    }
</script>
</body>

Web Storage vs Cookies

The benefit to using the Web Storage API instead of cookies is that the data resides locally and stays local.

Data stored in web storage is organized by root domain. The space allotment is available on a per–root domain basis. For example, domains such as ocalhostl or infocodify.com each get their own secure web storage space.

Web storage allows storage only of key/value pairs where the key and the value component are stored as a string.


Ads Right