Skip to content

Instantly share code, notes, and snippets.

@halfninja
Created April 28, 2009 20:12
Show Gist options
  • Save halfninja/103370 to your computer and use it in GitHub Desktop.
Save halfninja/103370 to your computer and use it in GitHub Desktop.
sessionStorage wrapper
// Data stored in DOM Session Storage (on supported browsers).
// create the SessionObject with a unique key name, then put data
// in to the data property. It will be JSONified to and fro automatically
// between page loads.
var SessionObject = function(key) {
this.data = null;
this.key = key;
this.store = window.sessionStorage;
if (this.store[this.key])
{
this.data = (""+this.store[this.key]).evalJSON();
}
Element.observe(window, 'beforeunload', function(){
this.store[this.key] = this.data.toJSON();
}.bind(this));
};
SessionObject.isSupported = function() {
return (!!window.sessionStorage);
};
//Example
var cart = new SessionObject('ShoppingCart');
cart.data = cart.data || [];
cart.data.push({id:1234, name:'Sweet Cuppin Cakes'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment