Wednesday, July 18, 2012

HTML5 localStorage

Persistent Client-Side Key-Value Pairs

The localStorage object has four primary method:
  • localStorage.clear()

  • localStorage.getItem( key )

  • localStorage.removeItem( key )

  • localStorage.setItem( key, value )

When dealing with the localStorage object, it is important to remember that, like cookies, you are dealing with string values. Both the key and the value arguments must be strings. And, while the browser might not throw an error if you pass-in non-string values, you'll quickly find that it is simply calling the toString() method implicitly.

Run the following sample code and check the console:
<html>
<head>
<script type="text/javascript">
console.log("tim in localStorage —",("tim" in localStorage));
console.log("localStorage.getItem( tim ) —",localStorage.getItem( "tim" ));
localStorage.setItem( "tim", "nice" );
localStorage[ "bad" ] = "awesome";
console.log("tim in localStorage —",("tim" in localStorage));
console.log("localStorage.getItem( ‘bad’ ) —",localStorage.getItem( "bad" ));
var myObject = {};
localStorage.setItem( "myObject", myObject );
console.log("typeof( myObject ) —",typeof( localStorage.getItem( "myObject" )));
localStorage.removeItem( "tim" );
delete localStorage[ "bad" ];
console.log("tim in localStorage —",("tim" in localStorage));
console.log("bad in localStorage —",("bad" in localStorage));
var clientId;
var id = localStorage.getItem(clientId);
if (!id) {
id = Math.floor(Math.random()*10000);
localStorage[clientId] = id;
}
var x = "new";
localStorage[x] = "killer";
console.log(localStorage.getItem(x));
</script>
</head>
<body></body>
</html>