bevacqua / local-storage

:left_luggage: A simplified localStorage API that just works
https://ponyfoo.com
MIT License
523 stars 62 forks source link

Fixed unhandled disabled localStorage crash exception #34

Closed DevJett closed 1 year ago

DevJett commented 3 years ago

Actually, the operation in the ls variable that checks if localStorage is enabled is insecure and it causes crashes the SPA's such as ReactJS. For example, if we try to import ls from "local-storage" in Codesandbox live editor it's going to crash the whole application even though we didn't use the local-storage functions yet. See the problem here: codesandbox

I just fixed that with try,catch, and tested all the following functions

    ls.set('test','value');
    ls.get('test');
    ls.remove('test');
    ls.backend();
    ls.on();
    ls.off();

Also, we no longer need to use the try,carch in set function since the ls variable is secure now, and I don't know why you are returning a boolean, is that important?

DevJett commented 3 years ago

To make it extera secure we can do it like so

try{
  localStorage.setItem('t.e.s.t', 'test');
  localStorage.removeItem('t.e.s.t');
  if('localStorage' in global && global.localStorage){
    ls =  global.localStorage ;
  }
}catch (e){
  console.error(`Access denied! Failed to read the 'localStorage' property from 'Window': Access is denied for this document`)
}