Local Storage in HTML5

Course- Javascript >

HTML5 pages can store even large amounts of data within the user’s browser, without any negative effect on the website’s performance. Web storage is more secure and faster than doing this via cookies. Like when using cookies, the data is stored in key/value pairs, and a web page can only access the data it has itself stored. The two new objects for storing data locally in the browser are

  • localStorage—Stores data with no expiration date
  • sessionStorage—Stores data just for the current session

If you’re unsure about your browser’s support for local storage, once again you can use feature detection:

if(typeof(Storage)!=="undefined") {
... both objects are available ...
}                 
                 

To store a value you can invoke the setItem method, passing to it a key and a value:

localStorage.setItem("key", "value");

Alternatively, you can use the localStorage object like an associative array:

localStorage["key"] = "value";

Retrieving the values can use either of these methods too:

alert(localStorage.getItem("key")); or
alert(localStorage["key"]);