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 = {}; }
};
}
@jonathan-annett
Copy link

jonathan-annett commented Dec 28, 2019

I swear this is hand crafted (not minified)
i made it by editing the first post in this thread, hacking it about until it acheived full functionality in both node.js and chrome.

caveat - it uses proxies to acheive localStorage.item = value functionality. this might mean older browsers choke at it. which probably makes this whole effort nothing but an academic exercise.

it works with Object.keys, and you can get the keys by calling localStorage.keys() also

to prove it works (in chrome at least), you need to do "delete window.localStorage" before loading the script, or edit the argument at the end of the file to give it a different name

in node.js use

var localStorage = require("./localStorage.js") - or whatever you called it.

data is writen to ./localStorage.json in real time

in the browser it will just auto populate window.localStorage when the script loads, and saves data to the cookie "localStorage' - of courese.

for what it's worth, it coverts keynames into a hash of sorts - more of an alphanumeic index. this means you can literally use any string as a key, provided you use the getItem and setItem mechanism.

enjoy.

            (function (o,s,n,b,j,R,K,I,P,T,F,X,C,O,N,A) {
        if (!o.k) {
            var S=function(){},i,c,w=j.stringify[b](j),r=j.parse[b](j),u,
                z=function(x){delete o[x];},D=o.d,
                k=function(k){
                    i=K[I](k);if(i<0){i= K[n];K.push(k);}
                    return i[s](R); 
                },f=function(k,f){P[k]={enumerable:false,configurable:true,value:f};},
                
            L=o.l,LS,ls={},p,h;
            f("ikeys",function(){return P.keys.value().map(function(k,i){return i[s](R);});});
            f("keys",function(){return K.filter(function(k,i){return !!o[i[s](R)];});});
            f("setItem",function(i,v){c=k(i);o[c]=w(v);S();return o[c];});
            f("getItem",function(i){c=K[I](i);h=c[s](R);return c<0||!o[h]?u:r(o[h]);});
            f("removeItem",function(i){c=K[I](i);h=c[s](R);if(c>=0){i=o[h];z(c);S();return i;}});
            f("clear",function(){c=K[n];K.splice(0,c);for(i=0;i<c;i++){z(i[s](R));}S();});
            O.defineProperties(ls,P);
            p={
                get : function(x,k){ return P[k]?P[k].value:ls.getItem(k);},
                set : function(x,k,v){ if(!P[k]){ls.setItem(k,v);return true;}},
                ownKeys: function(){return K.filter(function(k,i){return !!o[i[s](R)];});},
                getOwnPropertyDescriptor : function(k) {
                  return {enumerable: true,configurable: true,};
                }
            };
            LS = new Proxy(ls,p);  
            o.x=function(i){O.keys(i).forEach(function(k){p.set(ls,k,i[k]);});};
            if (o.n) {
                module.exports=LS;
                A="./"+L+".json";
                N=require("fs");
                C=S;
                try{o.x(N.existsSync(A)?r(N.readFileSync(A)):{});}catch(e){}
                S=function(){
                   c=w(LS);
                   i=c.length>2;
                   D=i?"writeFile":"unlink";
                   N[ D ]("./"+L+".json",i?c:C,i?C:u);
                };
               
            } else {
                o.w[o.l]=LS;
                  c = D[C][X]( ';' ).map( function( x ) { return x.trim()[X]( '=' ); } ).reduce( 
                  function( a, b ) { a[ b[ 0 ] ] = b[ 1 ]; return a; }, {} )[ L ];
                  if (c) {
                      o.x(r(atob(c)));
                  }
                  S=function(){
                     c=w(LS);i=c.length>2;
                     D[C]= L+"="+ (i ? btoa(c) : "")+"; ; expires="+ ( i ? N : A) +" UTC; path=/"; 
                  };
            }
            "lwndkx"[X]('').forEach(z);
        }
    })((function (o,k) {
        try {
            o.l=k;
            o.w=window;
            o.d=document; 
            o.k=(k in o.w&&o.w[k]!==null);
        } catch (e) {
            o.w={};
            o.n=!0;
        }
        return o;
    })({},"localStorage"),"toString","length","bind",JSON,36,[],"indexOf",{},!0,!1,"split","cookie",Object,"Tue, 19 Jan 2038 03:14:07","Thu, 01 Jan 1970 00:00:00");

@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