Skip to content
Advertisement

Check if localStorage is available

I know there has been many questions about checking for localStorage but what if someone manually shuts it off in their browser? Here’s the code I’m using to check:

localStorage.setItem('mod', 'mod');
if (localStorage.getItem('mod') != null){
  alert ('yes');
  localStorage.removeItem('mod');
} else {
  alert ('no');
}

Simple function and it works. But if I go into my Chrome settings and choose the option “Don’t Save Data” (I don’t remember exactly what it’s called), when I try to run this function I get nothing but Uncaught Error: SecurityError: DOM Exception 18. So is there a way to check if the person has it turned off completely?

UPDATE: This is the second function I tried and I still get no response (alert).

try {
  localStorage.setItem('name', 'Hello World!');
} catch (e) {
  if (e == QUOTA_EXCEEDED_ERR) {
   alert('Quota exceeded!');
  }
}

Advertisement

Answer

Use modernizr‘s approach:

function isLocalStorageAvailable(){
    var test = 'test';
    try {
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
    } catch(e) {
        return false;
    }
}

if(isLocalStorageAvailable()){
    // available
}else{
    // unavailable
}

It’s not as concise as other methods but that’s because it’s designed to maximise compatibility.

The original source: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js

Working example: http://jsfiddle.net/6sm54/2/

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement