javascript 检查 localStorage 是否可用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16427636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if localStorage is available
提问by user2025469
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
但是如果有人在浏览器中手动关闭它怎么办?这是我用来检查的代码:
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?
简单的功能,它的工作原理。但是,如果我进入 Chrome 设置并选择“不保存数据”选项(我不记得它的确切名称),当我尝试运行此功能时,除了Uncaught Error: SecurityError: DOM Exception 18
. 那么有没有办法检查这个人是否完全关闭了它?
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!');
}
}
回答by Joe
Use modernizr
's approach (you might want to change my function name to something better):
使用modernizr
的方法(您可能希望将我的函数名称更改为更好的名称):
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
原文出处:https: //github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
Working example: http://jsfiddle.net/6sm54/2/
工作示例:http: //jsfiddle.net/6sm54/2/
回答by Frederik.L
I'd check that localStorage
is defined prior to any action that depends on it:
我会localStorage
在任何依赖于它的操作之前检查它的定义:
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
}
回答by Stijn de Witt
Feature-detecting local storage is tricky. You need to actually reach into it. The reason for this is that Safari has chosen to offer a functional localStorage
object when in private mode, but with it's quotum set to zero. This means that although all simple feature detects will pass, any calls to localStorage.setItem
will throw an exception.
特征检测本地存储很棘手。你需要真正接触它。这样做的原因是 Safari 选择localStorage
在私有模式下提供一个功能对象,但它的配额设置为零。这意味着尽管所有简单的功能检测都会通过,但任何调用localStorage.setItem
都会抛出异常。
Mozilla's Developer Network entry on the Web Storage API's has a dedicated section on feature detecting local storage. Here is the method recommended on that page:
Mozilla 的 Web Storage API 上的 Developer Network 条目有一个关于功能检测本地存储的专门部分。这是该页面上推荐的方法:
function storageAvailable(type) {
try {
var storage = window[type],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return false;
}
}
And here is how you would use it:
这是您将如何使用它:
if (storageAvailable('localStorage')) {
// Yippee! We can use localStorage awesomeness
}
else {
// Too bad, no localStorage for us
}
If you are using NPM, you can grab storage-availableusing
如果您使用NPM,你可以抓住存储提供使用
npm install -S storage-available
then use the function like so:
然后像这样使用函数:
if (require('storage-available')('localStorage')) {
// Yippee! We can use localStorage awesomeness
}
Disclaimer: Both the documentation section on MDN and the NPM package were authored by me.
免责声明:关于 MDN 和 NPM 包的文档部分都是由我创作的。
回答by mcmimik
MDN updatedthe storage detect function. In 2018, it's more reliable:
MDN更新了存储检测功能。在 2018 年,它更可靠:
function storageAvailable() {
try {
var storage = window['localStorage'],
x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage && storage.length !== 0;
}
}
Browsers that support localStorage will have a property on the window object named localStorage. However, for various reasons, just asserting that property exists may throw exceptions. If it does exist, that is still no guarantee that localStorage is actually available, as various browsers offer settings that disable localStorage. So a browser may supportlocalStorage, but not make it availableto the scripts on the page. One example of that is Safari, which in Private Browsing mode gives us an empty localStorage object with a quota of zero, effectively making it unusable. However, we might still get a legitimate QuotaExceededError, which only means that we've used up all available storage space, but storage is actually available. Our feature detect should take these scenarios into account.
See here for a brief history of feature-detecting localStorage.
支持 localStorage 的浏览器将在名为 localStorage 的窗口对象上有一个属性。但是,由于各种原因,仅仅断言属性存在可能会引发异常。如果确实存在,那仍然不能保证 localStorage 实际上可用,因为各种浏览器提供禁用 localStorage 的设置。因此,浏览器可能支持localStorage,但不使其可用于页面上的脚本。一个例子是 Safari,它在隐私浏览模式下为我们提供了一个空的 localStorage 对象,其配额为零,实际上使其无法使用。但是,我们可能仍然会得到一个合法的 QuotaExceededError,这仅意味着我们已经用完了所有可用的存储空间,但存储实际上是可用的. 我们的特征检测应该考虑到这些场景。
有关特征检测 localStorage的简要历史,请参见此处。
回答by luis moyano
With this function you can check if localstorage is available or not, and you keep under control the possible exceptions.
使用此功能,您可以检查 localstorage 是否可用,并控制可能出现的异常。
function isLocalStorageAvailable() {
try {
var valueToStore = 'test';
var mykey = 'key';
localStorage.setItem(mykey, valueToStore);
var recoveredValue = localStorage.getItem(mykey);
localStorage.removeItem(mykey);
return recoveredValue === valueToStore;
} catch(e) {
return false;
}
}
回答by Ronnie Royston
Modifying Joe's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...
修改 Joe 的答案以添加 getter 使其更易于使用。下面你简单地说:if(ls)...
Object.defineProperty(this, "ls", {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
});
回答by Brady
Here is an easy check:
这是一个简单的检查:
if(typeof localStorage === 'undefined'){
if(typeof localStorage === 'undefined'){
回答by Lucky W
Use this to check localStorage is set or not. Its help you to get status of Localstorage.
使用它来检查 localStorage 是否设置。它可以帮助您获取 Localstorage 的状态。
if( window.localStorage.fullName !== undefined){
//action
}else{
}