Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pacotole/17bd3d610f2e4d62f76e8135d3c72dcc to your computer and use it in GitHub Desktop.
Save pacotole/17bd3d610f2e4d62f76e8135d3c72dcc to your computer and use it in GitHub Desktop.
localStorage polyfill with cookie storage
try {
localStorage.setItem('test', 1);
localStorage.removeItem('test');
} catch(e) {
window.localStorage = {
_data : JSON.parse(document.cookie.replace(/(?:(?:^|.*;\s*)localStorage\s*\=\s*([^;]*).*$)|^.*$/, "$1") || '{}'),
_save : function() { document.cookie = "localStorage=" + JSON.stringify(this._data) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; },
setItem : function(id, val) { this._data[id] = String(val); this._save(); },
getItem : function(id) { return this._data.hasOwnProperty(id) ? this._data[id] : null; },
removeItem : function(id) { delete this._data[id]; this._save(); },
clear : function() { this._data = {}; this._save(); }
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment