Created
April 10, 2010 17:44
-
-
Save wavded/362189 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have to use localStore and not localStorage... because of some issue with Chrome... haven't tested recently to see if its fixed.