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

时间:2012-06-26 19:14:13

标签: javascript html html5

以下代码警告IE7中的ls exist

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

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

此外,我不想使用Modernizr,因为我只使用了一些HTML5功能,加载大型脚本不值得检测对这些内容的支持。

11 个答案:

答案 0 :(得分:93)

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

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;
    }
});

使用当前源代码

进行了更新

答案 1 :(得分:39)

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

答案 2 :(得分:16)

此功能正常工作:

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

来源:www.diveintohtml5.info

答案 3 :(得分:15)

  

我也不想使用Modernizr,因为我只使用了几个HTML5   功能和加载一个大脚本是不值得的只是检测   支持这些事情。

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

答案 4 :(得分:8)

尝试window.localStorage!==undefined

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

你也可以使用typeof window.localStorage!=="undefined",但上面的陈述已经做到了

答案 5 :(得分:7)

我没有在答案中看到它,但我认为很高兴知道你可以轻松地使用vanilla JS或jQuery进行这样简单的测试,而Modernizr帮助很多,有干净的没有它的解决方案。

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

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

或者,使用纯粹的Vanilla JavaScript

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

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

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

因此,整个想法是,无论何时需要JavaScript功能,您都应首先测试父对象,然后测试代码使用的方法。

答案 6 :(得分:3)

尝试catch将完成这项工作:

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

答案 7 :(得分:1)

尝试:

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

答案 8 :(得分:1)

if (window.localStorage){

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

}

答案 9 :(得分:0)

修改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>

答案 10 :(得分:0)

我知道我参加聚会有点晚了,但是我整理了一些有用的功能,并将其放入名为“ manage_storage.js”的文件中。我希望它们对你们一样有用,因为它们为我提供了很好的服务。

记住:您要查找的功能(回答此问题)是isLclStorageAllowed

因此,事不宜迟,这是我的代码:

/* 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] */