Skip to content

Instantly share code, notes, and snippets.

@Chofoteddy
Forked from jfsiii/gist:814784
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chofoteddy/db0973f7de90ef28ef7d to your computer and use it in GitHub Desktop.
Save Chofoteddy/db0973f7de90ef28ef7d to your computer and use it in GitHub Desktop.
get and set objects in localStorage and sessionStorage
// Forked from jfsiii https://gist.github.com/jfsiii/814784
// Forked from paul irish's https://gist.github.com/paulirish/601751
// 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)
// ^^^ Should be fixed now. Tested in FF 3.6 Mac OS X 10.6
// Fixed error with typeof == Number
// THIS IS INCOMPLETE CODE. would love any help if you'd like to help! :)
// Roger Raymond helped.
// John Schulz helped :)
// Christopher Castaneira helped :D
(function () {
var toString = Object.prototype.toString,
isArray = function (v) {
return (/^\[object Array\]$/).test(toString.call(v));
},
isObject = function (v) {
return (/^\[object Object\]$/).test(toString.call(v));
};
// Verifica sí get/setItem tienen soporte nativo para objetos
var nativeJSONStorage = (function () {
var feature_key = 'featureTest';
if (!window.sessionStorage) return false;
sessionStorage.setItem(feature_key, {});
var item = sessionStorage.getItem(feature_key),
bool = isObject(item) || isArray(item);
sessionStorage.removeItem(feature_key);
return bool;
})();
if (nativeJSONStorage) return;
if (window.Storage) {
var setter = Storage.prototype.setItem,
getter = Storage.prototype.getItem;
if (nativeJSONStorage) return;
Storage.prototype.setItem = function (k, v) {
var result;
if (isObject(v) || isArray(v)) result = setter.call(this, k, JSON.stringify(v));
else result = setter.apply(this, arguments);
return result;
};
Storage.prototype.getItem = function (k) {
var result = getter.apply(this, arguments);
try {
return JSON.parse(result);
} catch (e) {
return result;
}
};
}
})();
// tests
console.group('localStorage');
localStorage.setItem('storage', {local:true});
console.log(localStorage.getItem('storage') && localStorage.getItem('storage').local == true);
console.groupEnd('localStorage');
console.group('sessionStorage');
sessionStorage.setItem('storage', {session: true});
console.log(sessionStorage.getItem('storage') && sessionStorage.getItem('storage').session == true);
console.groupEnd('sessionStorage');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment