DEV Community

Discussion on: Vanilla JavaScript localStorage

Collapse
 
curiouskaran profile image
Karan Sharma

localStorage has many gotchas around it like different behavior in different browsers when localStorage is full also in browsers like safari you can't access or set localStorage when in incognito mode.

Collapse
 
dailydevtips1 profile image
Chris Bongers

It all comes with downsides indeed!
Not the most reliable storage, but a good alternative to keep in mind.

Collapse
 
merri profile image
Vesa Piittinen

And here is the shortest code to check to see if you can actually use the localStorage:

// usage: put return value to a variable or use as a if condition
!function(l){try{(l=localStorage).removeItem(l._='_')}catch(e){return 1}}()

You could also write a wrapper that would take care of cases like running out of localStorage space, but that is quite an overkill for most use cases. In the other hand if you do have lots of localStorage usage and/or need the abstraction (for code readability/maintenance reasons) then it will probably be worth it over a simple boolean check like the above.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Very nice quick check! Love it <3