Storing and Retrieving Data in Local Storage with HTML5

By Andy Harris

With HTML5, you can write up to 5MB of data to a special file on the client computer. All the pages that come from your domain share the same storage area, so you can use this mechanism to keep data persistent between multiple pages. The data also stays on the client machine (until you remove it), so it can be used to keep track of information over time.

First you write some code to store and retrieve information. For example, a code snippet that stores and retrieves the user’s name looks like this:

  function greet(){
    name = localStorage.getItem("name");
    if (name == null || name == "null"){
      alert("Hi, Stranger!");
      name = prompt("What is your name?");
      localStorage.setItem("name", name);
    } else {
      alert ("Hi, " + name + "!");
    } // end greet
  } // end function  

The retrieval process is pretty simple:

  1. Retrieve the value.

    Generally, you’ll create a variable with the same name as the key. Try to extract the value from the localStorage object with the getItem() method. Retrieving the data is like checking out a book from the library.

  2. Determine if the value exists.

    If the key does not exist, the value will be null. If that’s the case, do something to add a value. Note that some browsers look for the value null (a string value) and some actually use the keyword null (no quotes, because it’s a key word). Use the special operator || (or) to check for either possibility.

  3. Modify the variable.

    Your code will likely modify the variable.

  4. Store the value back in the database.

    The localStorage database is separated from your variables. It’s up to you to update any data you want to keep. Use the setItem() method to save data. This is like returning a book to the library.