Managing State Management in HTML5 Using Web Storage



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
  2. sessionStorage - stores data for one session(just like normal session object in

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:


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:


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>
<body bgcolor="aqua">
<script type="text/javascript">
if (localStorage.pagecount)
            localStorage.pagecount=Number(localStorage.pagecount) +1;
document.write("Total User Visits: " + localStorage.pagecount + " time(s).");
if (sessionStorage.pagecount)
  sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
document.write(" Visits "+sessionStorage.pagecount+" time(s) this session.")
<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>

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



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