O'Reilly logo

JavaScript Cookbook by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.5. Creating a localStorage Client-Side Data Storage Item


You want to shadow form element entries (or any data) in such a way that if the browser crashes, the user accidentally closes the browser, or the Internet connection is lost, the user can continue.


You could use cookies if the data is small enough, but that strategy doesn’t work in an offline situation. Another, better approach, especially when you’re persisting larger amounts of data or if you have to support functionality when no Internet connection is present, is to use the new localStorage:

var value = document.getElementById("formelem").value;
If (value) {
   localStorage.formelem = value;
// recover
var value = localStorage.formelem;
document.getElementById("formelem").value = value;


Recipe 20.4 covered sessionStorage, one of the new DOM Storage techniques. The localStorage object interface is the same, with the same approaches to setting the data:

// use item methods

// use property names directly
sessionStorage.keyName = "value:
localStorage.keyName = "value";

// use the key method
sessionStorage.key(0) = "value";
localStorage.key(0) = "value:

and for getting the data:

// use item methods
value = sessionStorage.getItem("key");
value = localStorage.getItem("key");

// use property names directly
value = sessionStorage.keyName:
value = localStorage.keyName;

// use the key method
value = sessionStorage.key(0);
value = localStorage.key(0):

Both also support the length property, which provides a count of stored item pairs, and the clear method (no parameters), which clears out all Storage (but Firefox only supports clearing storage for localStorage). In addition, both are scoped to the HTML5 origin, which means that the data storage is shared across all pages in a domain, but not across protocols (e.g., http is not the same as https) or ports.

The difference between the two is how long data is stored. The sessionStorage object only stores data for the session, but the localStorage object stores data on the client forever, or until specifically removed.

The sessionStorage and localStorage objects also support one event: the storage event. This is an interesting event, in that it fires on all pages when changes are made to a localStorage item. It is also an area of low-compatibility among browsers: you can capture the event on the body or document elements for Firefox, on the body for IE, or on the document for Safari.

Example 20-5 demonstrates a more comprehensive implementation than the use case covered in the solution for this recipe. In the example, all elements of a small form have their onchange event handler method assigned to a function that captures the change element name and value, and stores the values in the local storage via localStorage. When the form is submitted, all of the stored form data is cleared.

When the page is loaded, the form elements onchange event handler is assigned to the function to store the values, and if the value is already stored, it is restored to the form element. To test the application, enter data into a couple of the form fields—but, before clicking the submit button, refresh the page. Without the use of localStorage, you’d lose the data. Now, when you reload the page, the form is restored to the state it was in before the page was reloaded.

Example 20-5. Using localStorage to back up form entries in case of page reload or browser crash

<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
   window.onload=function() {
     try {
        var elems = document.getElementsByTagName("input");

        // capture submit to clear storage

        for (var i = 0; i < elems.length; i++) {

           if (elems[i].type == "text") {

              // restore
              var value = localStorage.getItem(elems[i].id);
              if (value) elems[i].value = value;

              // change event
       } catch (e) {

   // store field values
   function processField() {
     localStorage.setItem(this.id, this.value);

   // clear individual fields
   function clearStored() {
     var elems = document.getElementsByTagName("input");
     for (var i = 0; i < elems.length; i++) {

       if (elems[i].type == "text") {

   <form id="inputform">
      <label for="field1">Enter field1:</label> <input type="text" id="field1" />
<br /> <br />
      <label for="field2">Enter field2:</label> <input type="text" id="field2"
/><br /><br />
      <label for="field3">Enter field1:</label> <input type="text" id="field3" />
<br /> <br />
      <label for="field4">Enter field1:</label> <input type="text" id="field4" />
<br /> <br />
      <input type="submit" value="Save" />

The size alloted for localStorage varies by browser, and some browsers, such as Firefox, allow users to extend the Storage object limits.

The localStorage object can be used for offline work. For the form example, you can store the data in the localStorage and provide a button to click when connected to the Internet, in order to sync the data from localStorage to server-side storage.

See Also

See Recipe 20.4 for more on the Storage object, and on sessionStorage and localStorage.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required