Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs
Contact   •   Articles   •   Products   •   Support   •   Search
Ad-free experience sponsored by:
ASPOSE - the market leader of .NET and Java APIs for file formats – natively work with DOCX, XLSX, PPT, PDF, images and more

Using HTML 5 SessionState to save rendered Page Content


HTML 5 SessionState and LocalStorage are very useful and super easy to use to manage client side state. For building rich client side or SPA style applications it's a vital feature to be able to cache user data as well as HTML content in order to swap pages in and out of the browser's DOM. What might not be so obvious is that you can also use the sessionState and localStorage objects even in classic server rendered HTML applications to provide caching features between pages. These APIs have been around for a long time and are supported by most relatively modern browsers and even all the way back to IE8, so you can use them safely in your Web applications.

SessionState and LocalStorage are easy

The APIs that make up sessionState and localStorage are very simple. Both objects feature the same API interface which  is a simple, string based key value store that has getItem, setItem, removeitem, clear and  key methods. The objects are also pseudo array objects and so can be iterated like an array with  a length property and you have array indexers to set and get values with.

Basic usage  for storing and retrieval looks like this (using sessionStorage, but the syntax is the same for localStorage - just switch the objects):

// set
var lastAccess = new Date().getTime();
if (sessionStorage)
    sessionStorage.setItem("myapp_time", lastAccess.toString());

// retrieve in another page or on a refresh
var time = null;
if (sessionStorage)
    time = sessionStorage.getItem("myapp_time");
if (time) time = new Date(time * 1); else time = new Date();

sessionState stores data that is browser session specific and that has a liftetime of the active browser session or window. Shut down the browser or tab and the storage goes away. localStorage uses the same API interface, but the lifetime of the data is permanently stored in the browsers storage area until deleted via code or by clearing out browser cookies (not the cache). Both sessionStorage and localStorage space is limited. The spec is ambiguous about this - supposedly sessionStorage should allow for unlimited size, but it appears that most WebKit browsers support only 2.5mb for either object. This means you have to be careful what you store especially since other applications might be running on the same domain and also use the storage mechanisms. That said 2.5mb worth of character data is quite a bit and would go a long way.

The easiest way to get a feel for how sessionState and localStorage work is to look at a simple example.

You can go check out the following example online in Plunker:
http://plnkr.co/edit/0ICotzkoPjHaWa70GlRZ?p=preview

which looks like this:

Session Sample

Plunker is an online HTML/JavaScript editor that lets you write and run Javascript code and similar to JsFiddle, but a bit cleaner to work in IMHO (thanks to John Papa for turning me on to it).

The sample has two text boxes with counts that update session/local storage every time you click the related button. The counts are 'cached' in Session and Local storage. The point of these examples is that both counters survive full page reloads, and the LocalStorage counter survives a complete browser shutdown and restart. Go ahead and try it out by clicking the Reload button after updating both counters and then shutting down the browser completely and going back to the same URL (with the same browser). What you should see is that reloads leave both counters intact at the counted values, while a browser restart will leave only the local storage counter intact.

The code to deal with the SessionStorage (and LocalStorage not shown here) in the example is isolated into a couple of wrapper methods to simplify the code:

function getSessionCount() {
    var count = 0;
    if (sessionStorage) {
        var count = sessionStorage.getItem("ss_count");
        count = !count ? 0 : count * 1;                    
    }
    $("#txtSession").val(count);
    return count;
}
function setSessionCount(count) {
    if (sessionStorage)
        sessionStorage.setItem("ss_count", count.toString());
}

These two functions essentially load and store a session counter value. The two key methods used here are:

  • sessionStorage.getItem(key);
  • sessionStorage.setItem(key,stringVal);

Note that the value given to setItem and return by getItem has to be a string. If you pass another type you get an error. Don't let that limit you though - you can easily enough store JSON data in a variable so it's quite possible to pass complex objects and store them into a single sessionStorage value:

var user = { name: "Rick", id="ricks", level=8 }
sessionStorage.setItem("app_user",JSON.stringify(user));

to retrieve it:

var user = sessionStorage.getItem("app_user");
if (user)
    user = JSON.parse(user);

Simple!

If you're using the Chrome Developer Tools (F12) you can also check out the session and local storage state on the Resource tab:

SessionDebugger 

You can also use this tool to refresh or remove entries from storage.

What we just looked at is a purely client side implementation where a couple of counters are stored. For rich client centric AJAX applications sessionStorage and localStorage provide a very nice and simple API to store application state while the application is running.

But you can also use these storage mechanisms to manage server centric HTML applications when you combine server rendering with some JavaScript to perform client side data caching. You can both store some state information and data on the client (ie. store a JSON object and carry it forth between server rendered HTML requests) or you can use it for good old HTTP based caching where some rendered HTML is saved and then restored later.

Let's look at the latter with a real life example.

Posted in JavaScript  HTML5  ASP.NET  MVC  

The Voices of Reason


 

Doug Dodge
July 02, 2013

# re: Using HTML 5 SessionState to save rendered Page Content

Nice! This will come in handy.

Thanks Rick.

Dan Shand
July 03, 2013

# re: Using HTML 5 SessionState to save rendered Page Content

Great article Rick! I'm always impressed with the detail you provide.
FYI there is a typo in the link to the mobile version of the gorge.net site (next to the QRCode). Chrome was nice enough to suggest the correct url after clicking ;-)

Doug Dodge
July 03, 2013

# re: Using HTML 5 SessionState to save rendered Page Content

Slicker than a ‘aila puua

*g*

viral
January 09, 2016

# re: Using HTML 5 SessionState to save rendered Page Content

great tutorial rick!
i m used this sessionStorage for maintaining session in angularjs with mvc4 and work like charm.

thanks rick...

codeDevil
January 13, 2016

# re: Using HTML 5 SessionState to save rendered Page Content

Thanks rick for the article is their any way to store HTML <select> list on client side and load at page refresh.

Rick Strahl
January 13, 2016

# re: Using HTML 5 SessionState to save rendered Page Content

@codeDevil - sure. You can cache the underlying data, or cache the actual rendered HTML content of the list and then drop it back into the page the same way I do with the custom rendered list I used. It works with any HTML element as long as you have some wrapping element that you can select and capture the innerHtml from.

codeDevil
January 13, 2016

# re: Using HTML 5 SessionState to save rendered Page Content

thanks let me try using it .... problem i am trying to solve :

"I have a HTML page with couple of div and 2 drop down list . values in drop down list is loaded based on selection made in list 1 (both the list are getting values from DB), such that Every time user selects a value from drop down list 2 .. value is passed as as parameter and the page is reloaded to display the values in div present on the page.

Problem is with the refresh of page select list values are also refreshed and user is again asked to select the values from the list.

As per my knowledge we can store single values in cookies .. is it possible to store a list, also apart from cookies is there any other way to store entire drop down list on client side ?

I am using php for server side scripting and java script on client side "

Rick Strahl
January 13, 2016

# re: Using HTML 5 SessionState to save rendered Page Content

@codedevil - well if you capture the list you also need to capture the selected value and also store that. Typically you store the list and the selection as I do in my custom list above as well.
 

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2017