问题描述
我知道有关于检查 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设置并选择不要保存数据选项(我不记得它的名字),当我尝试运行这个函数时,只有未捕获的错误: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!');
}
}
推荐答案
使用的方法(您可能希望将我的功能名称更改为更好):
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.
原始来源:
工作示例:
这篇关于检查localStorage是否可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!