check if browser supports Local Storage

How to Check if Browser Supports Local Storage in HTML

If you are writing web applications that support offline data storage, then you will need to know if the browser supports local storage or not. Here's how you can check if the browser supports local storage:

Method 1: Using JavaScript


if (typeof(Storage) !== "undefined") {
  // Local storage is supported
  // Your code here
} else {
  // Local storage is not supported
  // Your code here
}

The above code checks if the Storage object is defined or not. If it is not undefined, it means that local storage is supported by the browser. You can then write your code for storing and retrieving data using local storage.

Method 2: Using Modernizr

Modernizr is a JavaScript library that detects HTML5 and CSS3 features in the user's browser. You can use Modernizr to detect if local storage is supported or not:


if (Modernizr.localstorage) {
  // Local storage is supported
  // Your code here
} else {
  // Local storage is not supported
  // Your code here
}

The above code checks if the localstorage property of the Modernizr object is true or false. If it is true, it means that local storage is supported by the browser.

Method 3: Using try-catch block

You can also check if local storage is supported by wrapping your code in a try-catch block:


try {
  localStorage.setItem('test', 'test');
  localStorage.removeItem('test');
  // Local storage is supported
  // Your code here
} catch (e) {
  // Local storage is not supported
  // Your code here
}

The above code tries to set and then remove an item from local storage. If there are no errors, it means that local storage is supported by the browser.

These are the three methods that you can use to check if the browser supports local storage. Choose the one that suits your needs and implement it in your code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe