检查 localStorage 是否可用 [英] Check if localStorage is available
问题描述
我知道有很多关于检查 localStorage
的问题,但是如果有人在浏览器中手动关闭它会怎样?这是我用来检查的代码:
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');
}
简单的功能,它的工作原理.但是,如果我进入 Chrome 设置并选择不保存数据"选项(我不记得它的确切名称),当我尝试运行此功能时,我只得到 Uncaught Error: SecurityError:DOM 异常 18
.那么有没有办法检查这个人是否完全关闭了它?
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!');
}
}
推荐答案
使用 modernizr
的方法(你可能想将我的函数名称更改为更好的名称):
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.
原文出处:https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
工作示例:http://jsfiddle.net/6sm54/2/
这篇关于检查 localStorage 是否可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!