Checking and Clearing Locally Stored Data with HTML5

With HTML5, you can write up to 5MB of data to a special localStorage database 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.

Checking the data

Sometimes, you'll want to step through all the data in the database. This is actually pretty easy to do with the length property and the keys() method. Check this example:

The process involves creating a for loop to step through all the key/value pairs:

Build a forloop to step through the data.

Use the localStorage.length property to determine how many times you'll need to step through the loop.

Find the next key. Use the loop counter (in this case i) to get the next key with localStorage.key(i).

Note that the order of the keys will not be predictable.

Retrieve the value associated with that key.

Use the standard localStorage.getItem() method with the key you've just retrieved.

Use the key and value.

At this point, you have a variable called key containing the current key, and another called value containing the value associated with that key. You can then print out the data to the page or do whatever else you want with it.

Clearing the data

It's possible (and easy) to clear any or all of the data in local storage. Use the locaStorage.clear() method to clear all the data associated with your website, or the localStorage.removeItem(key) method to remove a particular key/value pair: