问题描述
在IE7中,以下代码提示 ls存在
:
if (window.localStorage){
alert('ls exists');
} else {
alert('ls does not exist');
}
IE7并不真正支持本地存储,但它仍会提醒它。也许这是因为我在使用IE9开发工具的IE7浏览器和文档模式下使用IE9。或者,也许这只是测试LS是否受支持的错误方法。什么是正确的方法?
另外我不想使用Modernizr,因为我只使用少量的HTML5功能并且加载大型脚本不值得以检测对这些事情的支持。
您不必使用modernizr,但可以使用它们的方法来检测如果支持 localStorage
//在FF4中,如果禁用,window.localStorage应该=== null。
//通常,我们无法直接测试,需要在窗口中执行
//`('localStorage')&& `首先测试,否则Firefox会
//如果cookie被禁用,则会抛出bugzil.la/365772
//同样在iOS5& Safari私有浏览模式,尝试使用localStorage.setItem
//会抛出异常:
// QUOTA_EXCEEDED_ERRROR DOM异常22.
//特别是,getItem和removeItem调用不会抛出。
//因为我们被迫尝试/抓住这个,我们会进攻。
//只是FWIW:IE8兼容模式完全支持这些功能:
// www.quirksmode.org/dom/html5.html
//但IE8不支持使用本地文件
Modernizr.addTest('localstorage',function(){
var mod ='modernizr';
try {
localStorage.setItem(mod ,mod);
localStorage.removeItem(mod);
return true;
} catch(e){
return false;
}
}) ;
使用当前源代码更新
The following code alerts ls exist
in 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?
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.
You don't have to use modernizr, but you can use their method to detect if localStorage
is supported
modernizr at github
test for 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
这篇关于如何检测浏览器是否支持HTML5本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!