user2025469 user2025469 - 4 months ago 22
HTML Question

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!');
}
}

Joe Joe
Answer

Use modernizr's approach (you might want to change my function name to something better):

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

if(lsTest() === true){
    // 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/

Comments