Local Storage API in HTML 5

The HTML 5 specification allows web applications to store up to 5 MB of data per domain on the client side and the API that you can for it is is called localStorage, this is a sample web page that performs different localStorage API related operations.

<!doctype html>
<html>
  <head>
    <script>
      if(window["localStorage"]){
      // Inserting or updating a key/value
      localStorage.setItem("key1","First test value");  
      localStorage.setItem("key2","Second test value");  
      
      // Getting value of key from local storage
      console.log(localStorage.getItem("key1"));
      
      //Removing a key from the local storage
      localStorage.removeItem("key1");
      console.log(localStorage.getItem("key1"));
      
      //Iterate through all the keys and print them in key=value format
      for( var key in localStorage)
        console.log(key + " = "+localStorage[key]);
      
      //Iterate through all the keys and print them in key=value format
      for (var i = 0 ; i < localStorage.length;i++){
        var keyName = localStorage.key(i);
        console.log(keyName +" = "+ localStorage[key]);
      }  
      
      //Removing everything from localStorage
     localStorage.clear();
      }else{
        alert("Browser does not support localStorage");
      }
    </script>
  </head>
  <body>
   Hello from Local Storage API
  </body>

</html>
This is screen shot of how the keys stored in local Storage look like in Chrome.

2 comments:

  1. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.

    html5

    ReplyDelete