Click here to Skip to main content
15,879,326 members
Articles / Web Development / HTML

HTML5 Web Storage

Rate me:
Please Sign up or sign in to vote.
4.73/5 (50 votes)
6 Apr 2012CPOL5 min read 79K   52   15
How to use Web Storage to achieve some of the same functionality.

Image 1

Introduction

The issue of storing data in the browser has traditionally been solved by using HTTP cookies. Here, we will study about how to use Web Storage, another technology born out of the HTML5 movement, to achieve some of the same functionality.

Background

Web Storage is often lumped in with other technologies under the HTML5 umbrella, although it has now been moved to its own specification (http://dev.w3.org/html5/webstorage/) and is being developed independently from HTML5.

Unlike cookies, data stored in Web Storage remains on the client and is never transferred to the server. Cookies, in contrast, are sent back and forth between the browser and the server with each HTTP request. This limits the amount of data you can store as cookies, and if the server has no use for the data, the bandwidth used to transmit the cookies is wasted. Browsers impose hard limits on the number and size of cookies; to stay on the safe side, you should store no more than 50 cookies and 4 KB per domain.

Using Web Storage solves both of these problems. First, the data never leaves the browser. Second, it allows you to store a larger amount of data. The W3C currently recommends a limit of 5 MB, but browsers are allowed to prompt the user for permission if more space is needed. Current browsers allow at least 2 MB of Web Storage data.

There are other storage related developments as well. The FileSystem API (www.w3.org/TR/file-system-api/) is another proposed specification that aims to become a W3C Recommendation. With the FileSystem API, web applications get access to a sandboxed file system with a nice API for reading and writing file data, binary as well as text. Chrome is currently the only browser with any support for the FileSystem API.

If you’re more interested in databases, then you can look forward to the IndexedDB API (www.w3.org/TR/IndexedDB/). This API provides the functionality needed for storing large amounts of data as well the ability to perform fast searches on this data. Firefox and Chrome both support IndexedDB and Internet Explorer is expected to join them with Internet Explorer 10. 

Using the storage interface 

The Web Storage specification describes two storage objects, the local storage and the session storage, accessible through the global objects localStorage and sessionStorage. The storage objects use the same interface, which means that anything you can do with localStorage, you can also do with sessionStorage and vice versa.

Using the storage API  

The storage objects are essentially doors to different data containers maintained by the browser. The localStorage object is tied to the domain, and the stored data is kept alive until you remove it.
The storage API consists of just a few functions. To change a value or to add a new value, use the localStorage.setItem() method: 

C++
localStorage.setItem("myData", "This is my data"

The first argument is a unique key that identifies the data, and the second argument is the data you want to store. You can now retrieve the data with the localStorage.getItem() method:

var data = localStorage.getItem("myData");  

Even if you close the browser, reload the page, or call localStorage.getItem() from another page (on the same domain), the data is still there. 

Alternatively, you can access the data using square brackets notation. All the stored values are exposed as properties on the storage object:

var data = localStorage["myData"];
localStorage["myData"] = "This is my data"

You can, of course, also use dot notation:

var data = localStorage.myData;
localStorage.myData = "This is my data"

If you need to remove a stored value from the storage object, you can do so with the localStorage.removeItem() method:

localStorage.removeItem("myData");

Use the localStorage.clear() method if you need to clear everything from a storage object:

localStorage.clear(); // remove all stored data

Encoding complex data types

Web Storage is limited to string values, so you cannot store other data types without converting them to a string representation. You can easily get around this limit if you encode your data as JSON:

var data = {
key1 : "string",
key2 : true,
key3 : [1,2.3]
};
localStorage.setItem("myData", JSON.stringify(data)); 

When you read the data back, just remember to decode the JSON string:

var data = JSON.parse(localStorage.getItem("myData"));

Iterating over stored values  

The length property of the storage object is equal to the number of key/value pairs that you have saved: 

var numValues = localStorage.length; 

The localStorage.key() method takes a single argument, an index between 0 and length-1, and returns the name of the key in that position:

var data = localStorage.key(0); // name of key at index 0 

There is no guarantee that keys are in the order you added them, but the method can still be useful if, for example, you need to iterate over all the stored values: 

for (var i=0,key,value;i<localStorage.length;i++) {
key = localStorage.key(i);
value = localStorage.getItem(key);
console.log(key, value);
}

Note: The order of the key/value pairs is determined by the browser and can change when you add or remove an item. As long as you just read or write to existing keys, the order is untouched. 

Creating a simple text editor 

Time for a quick example. The code below shows the code for a crude text editor that remembers the text entered into a textarea. 

<textarea id="input"></textarea>
<script>
var input = document.getElementById("input");
input.value = localStorage.getItem("mytext") || "";
input.addEventListener("keyup", function() {
localStorage.setItem("mytext", input.value);
}, false);
</script>

When you load the page, the text is loaded into the textarea element from the localStorage object. The keyup event handler updates the stored value whenever you type in the field. Because the data is continuously saved in localStorage, you can close the window at any time and resume writing when you open the page again. 

You can even read the same data from a different page. The following code shows a read-only version that loads the text every 50 milliseconds.

<textarea id="input" disabled></textarea>
<script>
var input = document.getElementById("input");
setInterval(function() {
input.value = localStorage.getItem("mytext") || "";
}, 50);
</script>

If you load the two pages in separate windows and place them side by side, you see that the second window automatically updates as you type into the first.

Using session storage 

The session storage is available through the sessionStorage object and uses the same interface as localStorage. The difference between session storage and local storage lies in the lifetime and scope of the data. Data in the local storage is available to all browser windows and tabs that are viewing pages on the given domain, even after the user closes and opens the browser window. Session storage, in contrast, is tied to the browser session and is cleared when the browser session ends, which typically occurs when the window closes. 

Session storage is useful for data that you need to store temporarily but you want to be able to access as the user clicks through different pages. A common use case could be a shopping basket that persists across page views but is emptied when the user closes the browser window.

You access the session storage the same way you access the local storage. The following code shows the example to use session storage.

<textarea id="input"></textarea>
<script>
var input = document.getElementById("input");
input.value = sessionStorage.getItem("mytext") || "";
input.addEventListener("keyup", function() {
sessionStorage.setItem("mytext", input.value);
}, false);
</script> 

Try to enter some text, and you see that it is still there if you reload the page. If you close the browser or the tab, however, the text is cleared.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO SOFTLOGIC
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Pratik Bhuva29-Feb-16 21:38
professionalPratik Bhuva29-Feb-16 21:38 
Thanks for Sharing.
GeneralMy vote of 5 Pin
Christopher Sommers2-Apr-13 15:14
Christopher Sommers2-Apr-13 15:14 
GeneralMy vote of 4 Pin
rsjha21-Mar-13 20:09
rsjha21-Mar-13 20:09 
QuestionExport The Stored Values Pin
gaurish thakkar27-Aug-12 22:26
gaurish thakkar27-Aug-12 22:26 
AnswerRe: Export The Stored Values Pin
SamarRizvi5-Sep-12 5:39
SamarRizvi5-Sep-12 5:39 
GeneralRe: Export The Stored Values Pin
Sarathkumar Nallathamby7-Mar-13 19:38
professionalSarathkumar Nallathamby7-Mar-13 19:38 
GeneralMy vote of 5 Pin
Monjurul Habib10-May-12 19:31
professionalMonjurul Habib10-May-12 19:31 
GeneralRe: My vote of 5 Pin
SamarRizvi18-May-12 8:00
SamarRizvi18-May-12 8:00 
QuestionNice Article Pin
Shailesh Kumar Singh13-Apr-12 23:29
Shailesh Kumar Singh13-Apr-12 23:29 
AnswerRe: Nice Article Pin
SamarRizvi13-Apr-12 23:38
SamarRizvi13-Apr-12 23:38 
QuestionNice article Pin
Hidayat Abbas9-Apr-12 15:04
Hidayat Abbas9-Apr-12 15:04 
AnswerRe: Nice article Pin
SamarRizvi9-Apr-12 15:06
SamarRizvi9-Apr-12 15:06 
GeneralClear Pin
Robin Rizvi6-Apr-12 8:43
Robin Rizvi6-Apr-12 8:43 
GeneralRe: Clear Pin
SamarRizvi6-Apr-12 11:52
SamarRizvi6-Apr-12 11:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.