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

以下代码在 IE7中提醒 ls exist:

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

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

我也不想使用现代化,因为我只使用了一些 HTML5特性,加载一个大的脚本不值得仅仅为了检测对这些东西的支持。

85207 次浏览

Try 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

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

Try:

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

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

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.

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.

Try catch will do the job :

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


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


}

This function works fine:

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

Source: www.diveintohtml5.info

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.

If you use jQuery, you can do:

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

Or, with pure Vanilla 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 (_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.

Modifying Andrea's answer to add a getter makes it easier to use. With the below you simply say: 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>

I know I'm a little late to the party, but I have a few useful functions I cooked up and threw into a file named 'manage_storage.js'. I hope they are as useful to you guys, as they have served me well.

Remember: The function you're looking for (that answers this question) is isLclStorageAllowed.

So without further ado here is my code:

/* Conditional Function checks a web browser for 'session storage' support. [BEGIN] */


if (typeof isSessStorageAllowed !== 'function')
{
function isSessStorageAllowed()
{
if (!!window.sessionStorage && typeof sessionStorage.getItem === 'function' && typeof sessionStorage.setItem === 'function' && typeof sessionStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ss_test_itm_key = 'ss_test_itm_' + String(cur_tm);
var ss_test_val = 'ss_test_val_' + String(cur_tm);


sessionStorage.setItem(ss_test_itm_key, String(ss_test_val));


if (sessionStorage.getItem(ss_test_itm_key) == String(ss_test_val))
{
return true;
}
else
{
return false;
};


sessionStorage.removeItem(ss_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};


/* Conditional Function checks a web browser for 'session storage' support. [END] */


/* Conditional Function checks a web browser for 'local storage' support. [BEGIN] */


if (typeof isLclStorageAllowed !== 'function')
{
function isLclStorageAllowed()
{
if (!!window.localStorage && typeof localStorage.getItem === 'function' && typeof localStorage.setItem === 'function' && typeof localStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ls_test_itm_key = 'ls_test_itm_' + String(cur_tm);
var ls_test_val = 'ls_test_val_' + String(cur_tm);


localStorage.setItem(ls_test_itm_key, String(ls_test_val));


if (localStorage.getItem(ls_test_itm_key) == String(ls_test_val))
{
return true;
}
else
{
return false;
};


localStorage.removeItem(ls_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};


/* Conditional Function checks a web browser for 'local storage' support. [END] */


/* Conditional Function checks a web browser for 'web storage' support. [BEGIN] */


/* Prerequisites: 'isSessStorageAllowed()', 'isLclStorageAllowed()' */


if (typeof isWebStorageAllowed !== 'function')
{
function isWebStorageAllowed()
{
if (isSessStorageAllowed() === true && isLclStorageAllowed() === true)
{
return true;
}
else
{
return false;
};
};
};


/* Conditional Function checks a web browser for 'web storage' support. [END] */