HTML5 localStorage

Local Storage
Local Storage

Local Storage is just a part of the Web Storage api. HTML 5 has a feature that is supported even in IE 8 that allows web developers to store data locally without using cookies. The operating system on the computer provides tools directly to the applications for storing and retrieving data for the application. This information can be stored in .INI files, preference files, XML files, and many other places depending upon your operating system and the application you’re using. But web applications don’t have this type of storage. The closest thing we have to a local storage tool is a cookie. Using a cookie, web developers can store a small amount of information (typically no more than 4 KB). But the current HTML 5 Storage specification says that browsers should set a limit of 5MB per origin (host or domain).

Unlike just about every other new feature in HTML 5, Internet Explorer 8 supports localstorage! It is also supported by Firefox 3.5, Safari 4, Chrome 4, Opera 10.5, iOs 2, and Android 2.
Local Storage is intended to be used for storing and retrieving data in html pages from the same domain. The data can be retrieved from all the windows in the same domain even if the browser is restarted. The Session Storage is the other Web Storage option and the data is available only in the window it was stored in and is lost when the browser window is closed.

Checking browser supports Local Storage

1
2
3
4
5
6
7
function testLocalStorage()
{
if (localStorage)
return "Local Storage: Supported";
else
return "Local Storage: Unsupported";
}

Store a value in local storage

1
2
localStorage.setItem("key", "value");
localStorage["key"] = "value";

Retrieve a Value

1
2
alert(localStorage.getItem("key"));
alert(localStorage["key"]);

List all stored values

1
2
3
4
5
6
function AllLocalVariables(){
for (i=0; i {
key = localStorage.key(i);
val = localStorage.getItem(key);
}
}

Remove a Value

1
void removeItem("key");

Clear all the values

1
localStorage.clear();