TK1*_*123 80 html javascript html5
ls existIE7中的以下代码警报:
if(window.localStorage) {
alert('ls exists');
} else {
alert('ls does not exist');
}
Run Code Online (Sandbox Code Playgroud)
IE7并不真正支持本地存储,但这仍然会提醒它.也许这是因为我在IE7浏览器中使用IE9并使用IE9开发人员工具进行文档模式.或者这可能是测试LS是否支持的错误方法.什么是正确的方法?
此外,我不想使用Modernizr,因为我只使用了一些HTML5功能,加载一个大脚本不值得它只是为了检测对这些事情的支持.
And*_*eas 93
您不必使用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;
}
});
Run Code Online (Sandbox Code Playgroud)
使用当前源代码更新
小智 40
if(typeof Storage !== "undefined")
{
// Yes! localStorage and sessionStorage support!
// Some code.....
}
else
{
// Sorry! No web storage support..
}
Run Code Online (Sandbox Code Playgroud)
jua*_*nra 16
这个功能很好用:
function supports_html5_storage(){
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 15
此外,我不想使用Modernizr,因为我只使用了一些HTML5功能,加载一个大脚本不值得它只是为了检测对这些事情的支持.
要减少Modernizr文件大小,请在http://modernizr.com/download/上自定义文件以满足您的需求.仅有localStorage版本的Modernizr的版本为1.55KB.
试试window.localStorage!==undefined:
if(window.localStorage!==undefined){
//Do something
}else{
alert('Your browser is outdated!');
}
Run Code Online (Sandbox Code Playgroud)
你也可以使用typeof window.localStorage!=="undefined",但上面的陈述已经做到了
我没有在答案中看到它,但我认为很高兴知道你可以轻松地使用vanilla JS或jQuery进行这样简单的测试,而Modernizr帮助很多,有没有它的清洁解决方案.
如果你使用jQuery,你可以这样做:
var _supportsLocalStorage = !!window.localStorage
&& $.isFunction(localStorage.getItem)
&& $.isFunction(localStorage.setItem)
&& $.isFunction(localStorage.removeItem);
Run Code Online (Sandbox Code Playgroud)
或者,使用纯Vanilla JavaScript:
var _supportsLocalStorage = !!window.localStorage
&& typeof localStorage.getItem === 'function'
&& typeof localStorage.setItem === 'function'
&& typeof localStorage.removeItem === 'function';
Run Code Online (Sandbox Code Playgroud)
然后,您只需执行IF来测试支持:
if (_supportsLocalStorage) {
console.log('ls is supported');
alert('ls is supported');
}
Run Code Online (Sandbox Code Playgroud)
因此,整个想法是,无论何时需要JavaScript功能,您都应首先测试父对象,然后测试代码使用的方法.
| 归档时间: |
|
| 查看次数: |
71992 次 |
| 最近记录: |