Managing State Management in HTML5 Using Web Storage

In this article we will explain how to manage state in HTML5 using web storage.


Descriptions

Content

First of all state management means to maintain your browser data state after postback

from the server. In HTML5 we can maintain our data after postback also.

For doing that in HTML5 use the WEBSTORAGE API to maintain the state.

Now the key point is

Storing Data on the Client

HTML5 offers two new objects for storing data on the client:

  1. localStorage - stores data with no time limit(just like application state in asp.net)
  2. sessionStorage - stores data for one session(just like normal session object in asp.net)

In HTML5, the data is NOT passed on by every server request, but used ONLY when asked for; that means it is an asynchronous postback.

It is possible to store large amounts of data without affecting the website's performance.

The data is stored in different areas for different websites, and a website can only access data stored by it.

HTML5 uses JavaScript to store and access the data.

Now I will build a small example where we will use localstorage and session storage HTML5 object.

We will build a small web application where we will track the number of sites being visited by the user.

I just built it in a simple notepad and saved this file as .html.

Step 1:

Please see the following code segment:

HtmlWbStr1.gif

Here localstorage.pagecount means it will track each pagecount visited by the user.
Now if you close the browser and again open the site it will not reset the old cout data, it will remain the same as from the previous one. Actually it stores the record.

Step 2:

Now see the following code segment:

HtmlWbStr2.gif

The following code segment counts the number of times a user has visited a page, in the current session. That means that if you close the browser then the session will end and the counts will again be 0.

Now here is the full code:

<!DOCTYPE html>
<html>
<body bgcolor="aqua">
<script type="text/javascript">
if (localStorage.pagecount)
            {
            localStorage.pagecount=Number(localStorage.pagecount) +1;
            }else
            {
            localStorage.pagecount=1;
            }
document.write("Total User Visits: " + localStorage.pagecount + " time(s).");
if (sessionStorage.pagecount)
  {
  sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
  }
else
  {
  sessionStorage.pagecount=1;
  }
document.write(" Visits "+sessionStorage.pagecount+" time(s) this session.")
</script>
<p>Refresh the page to see the counter increase.</p>
<p>For in case for localStorage  Close the browser window, and try again, and the counter will continue.</p>
</body>
</html>

Now if you run the page it will look like as in the following picture:

HtmlWbStr3.gif

Conclusion

So in this article we have learned the use of web storage in HTML5.