Skip to content

Instantly share code, notes, and snippets.

@wavded
Created April 10, 2010 17:44
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 wavded/362189 to your computer and use it in GitHub Desktop.
Save wavded/362189 to your computer and use it in GitHub Desktop.
/* Overwrite localStorage w/ cookie-based storage if browser does not support */
if(typeof localStorage === "undefined" || localStorage === null){
(function(){
function getExpiration(isRemove){
var date = new Date();
if(isRemove){
date.setTime((+date)-1000); //sometime in past
} else {
date.setTime((+date)+30758400000); //356 days ahead
}
return date.toUTCString();
}
function checkReservedWords(test){
if(test === "setItem" || test === "getItem" ||
test === "removeItem" || test === "length" ||
test === "key"){
return true;
}
return false;
}
window.localStore = {
setItem: function(name,value){
if(checkReservedWords(name)){
throw "Cannot use the reserved word '"+name+"' for a localStore key";
return;
}
document.cookie = name+"="+value+"; expires="+getExpiration()+" path=/";
if(!name in this){
this.length++;
}
this[name] = ""+value;
},
key: function(index){
var i = 0;
for(var item in this){
if(checkReservedWords(item)){
continue;
}
if(i === index){
return item;
}
i++;
}
},
getItem: function(name){
return window.localStore[name];
},
removeItem: function(name){
if(name in this){
delete cookies[name];
document.cookie = name+"=; expires="+getExpiration(true)+" path=/";
this.length--;
}
},
length: 0
};
var cookies = document.cookie.split(";"),
len = cookies.length;
window.localStore.length = len;
while(len--){
var cookie = cookies[len].split("=");
window.localStore[cookie[0].replace(/^\s*/,"")] = cookie[1];
}
})();
} else {
window.localStore = localStorage;
}
@wavded
Copy link
Author

wavded commented Apr 10, 2010

Have to use localStore and not localStorage... because of some issue with Chrome... haven't tested recently to see if its fixed.

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