Skip to content

Instantly share code, notes, and snippets.

@juliocesar
Created April 18, 2011 23:19
Show Gist options
  • Star 54 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save juliocesar/926500 to your computer and use it in GitHub Desktop.
Save juliocesar/926500 to your computer and use it in GitHub Desktop.
This is the best localStorage polyfill in the world
// I mean, seriously, localStorage is supported even by your mum. How about instead of
// casing the feature out, you give users in-memory (stale) storage instead?
// If they close your application, they deserve to lose data anyway.
// if (!('localStorage' in window)) {
if (!Modernizr.localstorage) {
window.localStorage = {
_data : {},
setItem : function(id, val) { return this._data[id] = String(val); },
getItem : function(id) { return this._data.hasOwnProperty(id) ? this._data[id] : undefined; },
removeItem : function(id) { return delete this._data[id]; },
clear : function() { return this._data = {}; }
};
}
@juliocesar
Copy link
Author

I'm basically terrified looking at the traffic this has had over the years and I never received even a single notification for any of it.

Thanks, people! Yes, my original example is terrible.

@arcreative
Copy link

Not sure if this addresses the fact that private Safari threw an error on setItem in some versions... which is stupid, but still relevant. I'm just going to conveniently ignore it at this point though, and mute all my sentry/rollbar issues :-)

@josephrocca
Copy link

For those that want to "polyfill" the localStorage object due to it being blocked by an error like this: DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document. (usually due to an embedded frame when your site is used in incognito), you'll need to use defineProperty. For example, here's a super minimal polyfill that doesn't allow usage like localStorage.setItem("key", value), but does allow localStorage.key=value:

Object.defineProperty(window, 'localStorage', {value: new Proxy({}, {set:(obj,k,v)=>obj[k]=String(v)}) });

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