Skip to content

Instantly share code, notes, and snippets.

@paulirish
Created September 28, 2010 20:50
Show Gist options
  • Save paulirish/601751 to your computer and use it in GitHub Desktop.
Save paulirish/601751 to your computer and use it in GitHub Desktop.
localStorage and sessionStorage should accept objects
// desire: localStorage and sessionStorage should accept objects
// in fact they do according to spec.
// http://code.google.com/p/chromium/issues/detail?id=43666
// but so far that part isnt implemented anywhere.
// so we duckpunch set/getItem() to stringify/parse on the way in/out
// this seems to work in chrome
// but fails in FF (cant redefine setItem as a function, it just tostring's it)
// THIS IS INCOMPLETE CODE. would love any help if you'd like to help! :)
// Roger Raymond helped.
(function(){
var toString = Object.prototype.toString;
// do a feature test to see if get/setItem natively support objects..
var nativeJSONStorage = (function(){
if (!window.sessionStorage) return false;
sessionStorage.setItem('featureTest',{});
var bool = /^\[object Object\]$/.test( toString.call(sessionStorage.getItem('featureTest')) );
sessionStorage.removeItem('featureTest');
return bool;
})();
if (nativeJSONStorage) return;
if (window.localStorage && localStorage.setItem){
var set = localStorage.setItem,
get = localStorage.getItem,
uniq = (''+Math.random()).slice(-6) + 'json:';
localStorage.setItem = function(k,v){
// this logic to determine if we stringify could be stronger..
// might want to trycatch and only use json'd if it succeeds.
if ( /^\[object (Object|Array)\]$/i.test( toString.call(v) ) ){
return set.call(localStorage, k, uniq + JSON.stringify(v) );
}
else {
return set.apply(localStorage,arguments);
}
};
localStorage.getItem = function(k){
var result = get.apply(localStorage,arguments);
if (result.indexOf(uniq) === 0){
return JSON.parse( result.slice( uniq.length ) );
}
return result;
};
}
// TODO: do the whole thing over with sessionStorage.
// obv DRY that shit up.
})();
// tests
localStorage.setItem('sup',{omg:true});
localStorage.getItem('sup') && localStorage.getItem('sup').omg == true
@jfsiii
Copy link

jfsiii commented Feb 7, 2011

I think I got this to work in FF/Chrome by setting the methods via Storage.prototype

Take a look at https://gist.github.com/814784 and let me know what you think

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment