Persistent local storage with HTML5 Web Storage

HTML5 supports local storage with key-value pairs. The specification for local storage in HTML5 is called “Web Storage“. Storage is demonstrated in the example below by storing and retrieving an array of actors.

<!DOCTYPE html>

<html>
<head>
    <title>Local storage with HTML5 Web Storage</title>

    <script type="text/javascript">
        var output;

        // Checks if local storage is supported
        function storageSupported() {
            try {
              return 'localStorage' in window && window['localStorage'] !== null;
            } catch (e) {
              return false;
            }
        }

        // Stores dummy data
        function storeData(){
            output = document.getElementById('output');

            if(storageSupported()){
                // Store the JSON encoded array of actors
                localStorage["actors"] = '[{"actor":"Chuck Norris"},{"actor":"Steven Seagal"},{"actor":"Arnold Schwarzenegger"}]';
            } else {
                // Shown if the browser does not support HTML5 local storage
                output.innerHTML += "HTML5 local storage is not supported by your browser";
            }
        }

        // Outputs the stored key-value pairs
        function showStoredData(){
            // Retrieve the JSON encoded array and decode it
            var actors = eval(localStorage["actors"]);

            for(var i=0;i<actors.length;i++){
                output.innerHTML += "Actor: " + actors[i].actor + "\n";
            }

            output.innerHTML += "\nStored data: \n";

            // Output each key-value pair
            for(var key in localStorage){
                output.innerHTML += "Key: " + key + " Value: " + localStorage[key] + "\n";
            }

        }
    </script>
</head>

<body onload='storeData();showStoredData();'>

<pre id='output'></pre>

</body>
</html>

Output:

Actor: Chuck Norris
Actor: Steven Seagal
Actor: Arnold Schwarzenegger

Stored data:
Key: actors Value: [{"actor":"Chuck Norris"},{"actor":"Steven Seagal"},{"actor":"Arnold Schwarzenegger"}]
This entry was posted in JavaScript and tagged , , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?