How to detect if browser supports HTML5 Local Storage
Determine whether HTML5 Local Storage is supported using the following JavaScript snippet:
This method evaluates the presence and usability of localStorage
, constituting a fast and efficient way to get the desired information.
Taking browser quirks into account
Although the prior test can suffice in many contexts, it's not foolproof. There are quirky scenarios when localStorage
might behave in unanticipated ways. Let's introduce a more robust approach:
A bulletproof try/catch approach
Here try/catch
actively confirms whether Local Storage is operational by attempting to set and then remove an item. This method protects you from unexpected security exceptions that may arise in certain browsing modes.
The fine print of aggressive testing
Sometimes, browsers or settings may assert localStorage
is available, but rejects access attempts. For instance, when cookies are blocked or in private browsing mode, using localStorage
may trigger a security error. In these cases, a try/catch
block ensures smooth handling of such anomalies by capturing all errors and safely returning false
.
Expanding your detection toolkit
Harnessing Modernizr
Modernizr is a known player in the space of feature detection. It allows a customizable test for local storage:
Tailor Modernizr to only enact the specific tests you need, resulting in a lightweight script that fits like a glove, especially when you are building performance-critical applications.
Toying with other options
If you require transient storage across pages, consider using Session Storage. Check for its support like so:
This approach also uses try/catch
to validate Session Storage support, proving useful in cases like older versions of Internet Explorer, where detection isn't that straightforward.
Tricky browser and document modes
Particular attention needs to be paid to different browser and document modes. They often have an uncanny knack of throwing a spanner in the works when accessing and supporting Local Storage. Especially IE's document modes might give you a hard time, so don't forget your cup of resilience while testing!
Reading the code
Gain valuable insights from historical iterations of detection methods. The references should equip you with a prism into the evolution of Local Storage API.
Was this article helpful?