I was recently on a project where I needed a really flexible persistent data storage mechanism. Normally, this would be fairly easily handled via server-side data persistence code but in this case, each page of the app was basically a single-page XHR app in that to render the page required a JSONP call and lots of DOM insertion and manipulation. What I was trying to accomplish was back-button support for these dynamically rendered pages and as most know, hitting the back-button on dynamically rendered DOM elements won't set them back to their original state. To further complicate the problem, the pages were being built based on user input into search forms which included input fields, select boxes and even fly-out accordion style controls. Basically, I was dealing with storing a large amount of data across page views and cookies definitely were not the solution. Also considering that the browser requirements started at IE6, none of the current localstorage mechanisms were viable.

<strong>Persistent Session Variables in JavaScript</strong>

After searching quite a bit, I finally found a solution that worked like a charm. <a href="http://www.thomasfrank.se/">Thomas Frank</a> had created a library called <a href="http://www.thomasfrank.se/sessionvars.html">Sessvars.js</a> that leveraged the <em>window.name</em> attribute. The reason for using <em>window.name</em> is that values stored in it persist across page views making it ideal for my needs. The one caveat is that it can only store a string value which at first seemed to throw a wrench in my plans. I needed to store complex data, not just strings. Thankfully, Thomas had come up with a novel way of dealing with this by building a JSON stringifier which serializes and deserializes object data. This allowed me to create a complex data store that could then be converted to a string on the fly. Loved it!

What I did was grab the file name and used that as a key value to identify the specific information for that page. So my object would look something like this:

[sourcecode language="javascript"]
{ &quot;page1.html&quot; : { &quot;form&quot; : { &quot;wrapper&quot; : &quot;#search-box&quot;, 
							  &quot;hash&quot; = &quot;field1=foo&amp;field2=21&amp;field3=Mike&quot; } },
	  		     &quot;callback&quot; : &quot;resetWrapper&quot; },
{ &quot;page2.html&quot; : { &quot;form&quot; : { &quot;wrapper&quot; : &quot;#adv-search-box&quot;, 
							  &quot;hash&quot; = &quot;field21=red&amp;field22=blue&amp;field56=February&quot; } } 
	  		     &quot;callback&quot; : &quot;resetWrapper&quot; },							  
{...
}
[/sourcecode]

The benefit of this is that it allowed me total flexibility in storing not only the affected form fields for that specific page as well as allowing for unique form field names on a page by page basis. I could also nest the data as deep as I wanted (i.e.: object within object).

Actually storing that data was extremely easy. I simply defined Sessvars.js in my document:
[sourcecode language="javascript"]
&lt;script type=&quot;text/javascript&quot; src=&quot;sessionvars.js&quot;&gt;&lt;/script&gt;
[/sourcecode]

and then stored my data into a property that I created in the default sessvars object:

[sourcecode language="javascript"]
sessvars.myObj = { &quot;page1.html&quot; : { &quot;form&quot; : { &quot;wrapper&quot; : &quot;#search-box&quot;, 
							  &quot;hash&quot; = &quot;field1=foo&amp;field2=21&amp;field3=Mike&quot; } },
	  		     &quot;callback&quot; : &quot;resetWrapper&quot; },
{ &quot;page2.html&quot; : { &quot;form&quot; : { &quot;wrapper&quot; : &quot;#adv-search-box&quot;, 
							  &quot;hash&quot; = &quot;field21=red&amp;field22=blue&amp;field56=February&quot; } } 
	  		     &quot;callback&quot; : &quot;resetWrapper&quot; },							  
{...
};
[/sourcecode]

The library attaches a method to the window's unload event which automatically handles the stringification of the JSON data once you leave the page so basically assigning the value is all I needed to do to persist the data.

<strong>Restoring the Page</strong>

The great thing about Sessvars.js is that when a page is loaded, it immediately restores the persistent data making it immediately accessible to your scripts. We were using jQuery on this project so I created a method that would determine the current page, search through my sessvars persistent data and if it found a key, reload the form with the user's values as well as re-run any previous JSONP calls to ensure the results were populated. I added the method in $(document).ready() to ensure it got called on every page load:

[sourcecode language="javascript"]
myApp.state = (function(){
	return {

		resetForm : function( key ) {
			if (sessvars.myApp.state[key]) {
			    var o = {};
			    var queryString = decodeURIComponent( sessvars.myApp.state[key].form.hash );
			    var wrapperEle = &quot;&quot;, formEle= &quot;&quot;, vals = &quot;&quot;;
			    
			    queryString.replace(/([^=]+)\=([^&amp;]+)&amp;?/ig, function(item, a, b){
			    	a = a.replace( /\&amp;/g, &quot; &quot;);
			    	b = b.replace( /\+/g, &quot; &quot;);
			    	if (o[a] &amp;&amp; typeof o[a] !== &quot;object&quot;) {
						o[a] = o[a] + &quot;,&quot; + b;
					} else {
						o[a] = b;
					}
				});	 		    
	    
	    		wrapperEle = $( sessvars.myApp.state[key].form.wrapper );
	    
		    	for (var index in o) { 
			   		vals = o[index].split( &quot;,&quot; );
			   		
			   		formEle = wrapperEle.find(&quot;input[name=&quot; + index + &quot;], select[name=&quot; + index + &quot;]&quot;);

			   		if (formEle.length &gt; 0) {
			   		
				   		if (formEle[0].tagName == &quot;INPUT&quot; &amp;&amp; (formEle[0].type == &quot;checkbox&quot; || formEle[0].type == &quot;radio&quot;)){
				   			formEle.attr( &quot;checked&quot;, &quot;&quot;);
				   			for (var i=0; i &lt; vals.length; i++) {
		   	   			
				   	   			if (index == &quot;accordianSet&quot;) {
					   	   			wrapperEle.find(&quot;input[name=&quot; + index + &quot;][value=&quot; + vals[i] + &quot;]&quot;).trigger( &quot;click&quot; );	
				   	   			} else {
									wrapperEle.find(&quot;input[name=&quot; + index + &quot;][value=&quot; + vals[i] + &quot;]&quot;).attr( &quot;checked&quot;, &quot;true&quot; );				   	   			
				   	   			}
				   	   			
				   			}
				   		} else {
				   			formEle.val( o[index] );
						}
						
					}
				}
    		}			
		},
		resetPage : function( key ) {

			if (sessvars.myObj.state[key]) {
				this.resetForm( key );
			}
			
			.... call various other methods to reset the page ....
			
		};

}());

$(document).ready( function(){
	myApp.state.resetPage( myApp.utils.getPageName() );
});
[/sourcecode]

The result is that the search forms would get repopulated with the previously entered values and and the JSONP call re-run based on these new values. It worked exactly like we needed it.

<strong>Closing Thoughts</strong>

Using Sessvars.js definitely helped us out of a jam. After looking at a number of back-button solutions and even updating <em>window.location</em>, this turned out to be the best solution for our needs due to the dynamic nature of every page. The other takeaway is that using <em>window.name</em> safely affords you about 2mb of data storage. I say this because of the testing that Thomas did. In his research he found the following:

<blockquote>
IE7 gave up at 32 Mb with a "out of memory" error. Firefox gave up at 32-64 Mb -sometimes crashed there about - otherwise threw an "out of memory" error.Safari gave up at 64 Mb and crashed. Opera has a limit built in (wise) and gave up after 2 Mb, throwing the error "Object to large (implementation limit.)"</blockquote>

I've not tested this out in newer versions of the browser so I can't say if these limits are still set but for this project, 2mb was more than enough for our needs.

<strong><em>Update:</em></strong>

Since posting this I've been sent two other JS-based storage solutions which are definitely worth looking at:

<a href="http://gist.github.com/350433">Storage Pollyfiller</a> by insanely talented developer Remy Sharp
<a href="http://github.com/brianleroux/lawnchair">LawnChair</a> by uber-JS ninja Brian Leroux
 

