One of our projects serves thousands of users every day. The users are non-technical and have all sorts of technical devices. The devices may be old and outdated, but they’re still used. We need to ensure the website works on such devices too.
All major browsers support localStorage
. It’s a default feature in modern browsers and we as developers use it as if it’s available in every client. But as always, you can’t be sure that the global localStorage
property is present. This tutorial shows you how to determine whether local storage is available in the client’s browser.
JavaScript Series Overview
- Get the Current URL
- Get URL Query Parameters
- How to Smooth Scroll to an HTML Element
- Sort a Set
- New, Immutable Array Methods
- Detect Network Error
- Create Array from AsyncIterable
- Using the new Array Grouping Methods
- Test for LocalStorage Support
- Get Battery Status
- Detect If a Device Battery Is Charging
Detect if LocalStorage is Available in the Browser
You may store data in the client’s browser using localStorage
. It’s a convenient data store without expiration time. It keeps data across browser sessions. This local cache may come in handy to display a possibly outdated version of that data until the refresh is finished.
But you shouldn’t assume that localStorage
is always available. Make sure that localStorage
is available in the client’s browser before using it. Otherwise, you’ll run into “cannot access property setItem on undefined”.
Here’s a isLocalStorageAvailable
helper method detecting whether the client browser has the global localStorage
object available:
/**
* Determine whether the client supports localStorage and whether it works as expected.
*
* @returns {Boolean}
*/
function isLocalStorageAvailable () {
if (typeof localStorage !== 'undefined') {
try {
localStorage.setItem('feature_test', 'yes');
if (localStorage.getItem('feature_test') === 'yes') {
localStorage.removeItem('feature_test');
return true;
}
} catch (e) {
// localStorage is deactivated/not supported/not working as expected
}
}
return false;
}
Besides checking the availability for the global localStorage
object, we’re also checking whether a given implementation matches the defined specification. A possible polyfill could have a different implementation than the official spec.
This isLocalStorageAvailable
method returns a boolean, true
if local storage is supported, and false
if not.
That’s it!