Saturday, 13 November 2010

HTML5 - Storing Data on the Client

Using HTML5, you can save data on clients (browsers) in two ways.
  • localStorage - This stores data with no time limit.
  • sessionStorage - This stores data for one session only।
How to create and access a localStorage:

<script type=“text/javascript”>
localStorage.firstname="Abdul";
localStorage.lastname="Ahad";
document.write( localStorage.firstname + " " + localStorage.lastname);
</script>

The following example counts the number of times a user has visited a page:

<script type="text/javascript">
if (localStorage.pagecount)
{
localStorage.pagecount=Number(localStorage.pagecount) +1;
}
else
{
localStorage.pagecount=1;
}
document.write("Visits "+ localStorage.pagecount + " time(s).");
</script>

The sessionStorage method stores the data for one session. The data is deleted when the user closes the browser window.

<script type="text/javascript">
sessionStorage.firstname="Abdul";
sessionStorage.lastname="Ahad";
document.write( sessionStorage.firstname + " " + sessionStorage.lastname);
</script>

The following example counts the number of times a user has visited a page, in the current session:

<script type="text/javascript">
if (sessionStorage.pagecount)
{
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else
{
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>