Javascript 如何检测浏览器是否支持 HTML5 本地存储

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11214404/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:56:28  来源:igfitidea点击:

How to detect if browser supports HTML5 Local Storage

javascripthtml

提问by TK123

The following code alerts ls existin IE7:

以下代码ls exist在 IE7 中发出警报:

if(window.localStorage) {
    alert('ls exists');
} else {
    alert('ls does not exist');
}

IE7 doesn't really support local storage but this still alerts it does. Perhaps this is because I am using IE9 in IE7 browser and document modes using the IE9 developer tool. Or maybe this is just the wrong way to test if LS is supported. What is the right way?

IE7 并不真正支持本地存储,但这仍然会提醒它。也许这是因为我在 IE7 浏览器中使用 IE9,并且使用 IE9 开发人员工具的文档模式。或者这可能只是测试是否支持 LS 的错误方法。什么是正确的方法?

Also I don't want to use Modernizr since I am using only a few HTML5 features and loading a large script isn't worth it just to detect support for those few things.

此外,我不想使用 Modernizr,因为我只使用了一些 HTML5 功能,并且加载一个大脚本只是为了检测对这几件事的支持是不值得的。

回答by Andreas

You don't have to use modernizr, but you can use their method to detect if localStorageis supported

您不必使用 Modernizr,但您可以使用他们的方法来检测是否localStorage受支持

modernizr at github
test for localStorage

github上的modernizr
测试localStorage

// In FF4, if disabled, window.localStorage should === null.

// Normally, we could not test that directly and need to do a
//   `('localStorage' in window) && ` test first because otherwise Firefox will
//   throw bugzil.la/365772 if cookies are disabled

// Also in iOS5 & Safari Private Browsing mode, attempting to use localStorage.setItem
// will throw the exception:
//   QUOTA_EXCEEDED_ERRROR DOM Exception 22.
// Peculiarly, getItem and removeItem calls do not throw.

// Because we are forced to try/catch this, we'll go aggressive.

// Just FWIW: IE8 Compat mode supports these features completely:
//   www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files

Modernizr.addTest('localstorage', function() {
    var mod = 'modernizr';
    try {
        localStorage.setItem(mod, mod);
        localStorage.removeItem(mod);
        return true;
    } catch(e) {
        return false;
    }
});

updated with current source code

使用当前源代码更新

回答by Brandon Ferrara

if(typeof Storage !== "undefined")
  {
  // Yes! localStorage and sessionStorage support!
  // Some code.....
  }
else
  {
  // Sorry! No web storage support..
  }

回答by juanra

This function works fine:

此功能工作正常:

function supports_html5_storage(){
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch(e) {
        return false;
    }
}

Source: www.diveintohtml5.info

资料来源:www.diveintohtml5.info

回答by Steve A

Also I don't want to use Modernizr since I am using only a few HTML5 features and loading a large script isn't worth it just to detect support for those few things.

此外,我不想使用 Modernizr,因为我只使用了一些 HTML5 功能,并且加载一个大脚本只是为了检测对这几件事的支持是不值得的。

To reduce Modernizr file size customize the file at http://modernizr.com/download/to fit your needs. A localStorage-only version of Modernizr comes in at 1.55KB.

要减小 Modernizr 文件大小,请在http://modernizr.com/download/上自定义文件以满足您的需要。Modernizr 的仅 localStorage 版本大小为 1.55KB。

回答by Danilo Valente

Try window.localStorage!==undefined:

尝试window.localStorage!==undefined

if(window.localStorage!==undefined){
    //Do something
}else{
    alert('Your browser is outdated!');
}

You can also use typeof window.localStorage!=="undefined", but the statement above already does it

您也可以使用typeof window.localStorage!=="undefined",但上面的语句已经做到了

回答by Ovi Trif

I didn't see it in the answers, but I think it's good to know that you can easily use vanilla JS or jQuery for such simple tests, and while Modernizr helps a lot, there are clean solutions without it.

我没有在答案中看到它,但我认为很高兴知道您可以轻松地使用 vanilla JS 或 jQuery 进行此类简单的测试,虽然 Modernizr 有很大帮助,但没有它也有干净的解决方案。

If you use jQuery, you can do:

如果您使用jQuery,则可以执行以下操作:

var _supportsLocalStorage = !!window.localStorage
    && $.isFunction(localStorage.getItem)
    && $.isFunction(localStorage.setItem)
    && $.isFunction(localStorage.removeItem);

Or, with pure Vanilla JavaScript:

或者,使用纯香草JavaScript

var _supportsLocalStorage = !!window.localStorage
    && typeof localStorage.getItem === 'function'
    && typeof localStorage.setItem === 'function'
    && typeof localStorage.removeItem === 'function';

Then, you would simply do an IF to test the support:

然后,您只需执行 IF 来测试支持:

if (_supportsLocalStorage) {
    console.log('ls is supported');
    alert('ls is supported');
}

So the whole idea is that whenever you need JavaScript features, you would first test the parent object and then the methods your code uses.

所以整个想法是,每当您需要 JavaScript 功能时,您首先要测试父对象,然后测试您的代码使用的方法。

回答by Mohit Verma

Try catch will do the job :

尝试 catch 将完成这项工作:

    try{
       localStorage.setItem("name",name.value);
       localStorage.setItem("post",post.value);
       }
    catch(e){
       alert(e.message);    
       }

回答by Darren

if (window.localStorage){

   alert('localStorage is supported');
   window.localStorage.setItem("whatever", "string value");

}

回答by ErJab

Try:

尝试:

if(typeof window.localStorage != 'undefined') {
}

回答by Ronnie Royston

Modifying Andrea's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...

修改 Andrea 的答案以添加 getter 使其更易于使用。下面你简单地说:if(ls)...

  var ls =  {
    get: function () { 
      var test = 'test';
      try {
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
      } catch(e) {
        return false;
      }
    }
  };

var ls =  {
  get: function () { 
    var test = 'test';
    try {
      localStorage.setItem(test, test);
      localStorage.removeItem(test);
      return true;
    } catch(e) {
      return false;
    }
  }
};

function script(){
  if(ls){
    alert('Yes');
  } else {
    alert('No');
  }
}
<button onclick="script()">Local Storage Support?</button>