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!'); } }
To check if a key exists or not in localStorage, we can use the localStorage. getItem() method. The localStorage. getItem() method takes the key as an argument and returns the key's value.
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/
I'd check that localStorage
is defined prior to any action that depends on it:
if (typeof localStorage !== 'undefined') { var x = localStorage.getItem('mod'); } else { // localStorage not defined }
UPDATE:
If you need to validate that the feature is there and that it is also not turned off, you have to use a safer approach. To be perfectly safe:
if (typeof localStorage !== 'undefined') { try { localStorage.setItem('feature_test', 'yes'); if (localStorage.getItem('feature_test') === 'yes') { localStorage.removeItem('feature_test'); // localStorage is enabled } else { // localStorage is disabled } } catch(e) { // localStorage is disabled } } else { // localStorage is not available }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With