Skip to content

Instantly share code, notes, and snippets.

@mckamey
Forked from remy/gist:350433
Created January 23, 2012 17:49
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 mckamey/1664497 to your computer and use it in GitHub Desktop.
Save mckamey/1664497 to your computer and use it in GitHub Desktop.
Storage polyfill
(function (window) {
'use strict';
if (window.localStorage && window.sessionStorage) {
return;
}
// initialize if data already stored
var data = JSON.parse(window.name || '{}');
var setData = function() {
window.name = JSON.stringify(data);
};
var Storage = function(type) {
return {
length: 0,
clear: function() {
for (var k in data) {
// remove all keys with prefix
if (k && k.indexOf(type) === 0) {
delete data[type+k];
this.length--;
}
}
setData();
},
getItem: function(key) {
return (type+key in data) ? data[type+key] : null;
},
key: function(i) {
// not perfect, but works
var ctr = 0;
for (var k in data) {
if (k && (k.indexOf(type) === 0) && (ctr++ === i)) {
return k.substr(type.length);
}
}
return null;
},
removeItem: function(key) {
if (type+key in data) {
delete data[type+key];
this.length--;
setData();
}
},
setItem: function(key, value) {
if (!(type+key in data)) {
this.length++;
}
data[type+key] = ''+value; // force the value to a string
setData();
}
};
};
// NOTE: local storage is stored with session but better than filling cookies
if (!window.localStorage) { window.localStorage = new Storage('L$'); }
if (!window.sessionStorage) { window.sessionStorage = new Storage('S$'); }
})(window);
(function(b){if(!b.localStorage||!b.sessionStorage){var c=JSON.parse(b.name||"{}"),f=function(){b.name=JSON.stringify(c)},g=function(d){return{length:0,clear:function(){for(var a in c)a&&0===a.indexOf(d)&&(delete c[d+a],this.length--);f()},getItem:function(a){return d+a in c?c[d+a]:null},key:function(a){var b=0,e;for(e in c)if(e&&0===e.indexOf(d)&&b++===a)return e.substr(d.length);return null},removeItem:function(a){d+a in c&&(delete c[d+a],this.length--,f())},setItem:function(a,b){d+a in c||this.length++;
c[d+a]=""+b;f()}}};if(!b.localStorage)b.localStorage=new g("L$");if(!b.sessionStorage)b.sessionStorage=new g("S$")}})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment