我知道有很多关于检查 localStorage
的问题,但是如果有人在浏览器中手动将其关闭怎么办?这是我用来检查的代码:
localStorage.setItem('mod', 'mod');
if (localStorage.getItem('mod') != null){
alert ('yes');
localStorage.removeItem('mod');
} else {
alert ('no');
}
简单的功能,它的工作原理。但是,如果我进入我的 Chrome 设置并选择选项“不保存数据”(我不记得它到底叫什么),当我尝试运行此功能时,我除了 Uncaught Error: SecurityError: DOM Exception 18
什么也得不到。那么有没有办法检查这个人是否完全关闭了它?
更新:这是我尝试的第二个功能,但我仍然没有收到任何响应(警报)。
try {
localStorage.setItem('name', 'Hello World!');
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!');
}
}
原文由 user2025469 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用
modernizr
的方法:它不像其他方法那样简洁,但这是因为它旨在最大限度地提高兼容性。
原始出处: https ://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
工作示例:http: //jsfiddle.net/6sm54/2/