Skip to content

Instantly share code, notes, and snippets.

@mundry
Created December 14, 2013 19:00
Show Gist options
  • Save mundry/7963392 to your computer and use it in GitHub Desktop.
Save mundry/7963392 to your computer and use it in GitHub Desktop.
Less exact but IE6 compatible imitation of the localStorage object to provide localStorage in browsers that don't support it by using cookies.
// https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#Compatibility
// Note: The maximum size of data that can be saved is severely
// restricted by the use of cookies. With this algorithm, use the
// functions localStorage.getItem(), localStorage.setItem(), and
// localStorage.removeItem() to get, add, change, or remove a key. The
// use of method localStorage.yourKey in order to get, set, or delete a
// key *is not permitted with this code*. You can also change its name
// and use it only to manage a document's cookies regardless of the
// localStorage object.
//
// Note: By changing the string
// "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/" to: "; path=/"
// (and changing the object's name), this will become a sessionStorage
// polyfill rather than a localStorage polyfill. However, this
// implementation will share stored values across browser tabs and
// windows (and will only be cleared when all browser windows have been
// closed), while a fully-compliant sessionStorage implementation
// restricts stored values to the current browsing context only.
if (!window.localStorage) {
window.localStorage = {
getItem: function (sKey) {
if (!sKey || !this.hasOwnProperty(sKey)) { return null; }
return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
},
key: function (nKeyId) {
return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]);
},
setItem: function (sKey, sValue) {
if (!sKey) { return; }
document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
this.length = document.cookie.match(/\=/g).length;
},
length: 0,
removeItem: function (sKey) {
if (!sKey || !this.hasOwnProperty(sKey)) { return; }
document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
this.length--;
},
hasOwnProperty: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
}
};
window.localStorage.length = (document.cookie.match(/\=/g) || window.localStorage).length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment