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:


  function viewData(){
//shows all the key / value pairs
for (i = 0; i < localStorage.length; i++){
key = localStorage.key(i);
value = localStorage.getItem(key);
alert(key + ": " + value);
} // end for loop

} // end viewData

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



  1. Build a for loop to step through the data.


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



  2. 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.



  3. Retrieve the value associated with that key.


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



  4. 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:


  function clearValues(){
alert("clearing " + name + " from the database...");
localStorage.removeItem("name");
localStorage.removeItem("count");
//to clear all values at once, you can use this:
//localStorage.clear();
//clean up display
lblCounter = document.getElementById("lblCounter");
lblCounter.innerHTML = "You have been here 0 times";
}



dummies

Source:http://www.dummies.com/how-to/content/checking-and-clearing-locally-stored-data-with-htm.html

No comments:

Post a Comment