javascript 如何检查localstorage是否可用?

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

how to check whether localstorage is available?

javascripthtmllocal-storage

提问by Manuel

W3Schools recommends (http://www.w3schools.com/html/html5_webstorage.asp)

W3Schools 推荐 ( http://www.w3schools.com/html/html5_webstorage.asp)

if(typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! No Web Storage support..
}

to check whether a local storage is available in the browser.

检查本地存储在浏览器中是否可用。

I use the following

我使用以下

var l=localStorage!==null?localStorage:0;
if(l) { /*code for locale storage*/}

and was wondering whether this is sufficient and reliable on all browsers?

并且想知道这是否在所有浏览器上都足够可靠?

Thx I really appreciate your help!

Thx 我真的很感谢你的帮助!

回答by gilly3

  1. w3fools– You seem to think that w3schools is associated with the w3c – they're not.

  2. Use window.localStorage. Without window, you'll get a ReferenceErrorin browsers that don't support localStorage.

  3. Don't use localStorage !== null. In non supporting browsers, localStoragewill be undefined, not null. The better operator would be != null, but I wouldn't use a comparison operator at all. You can just pass window.localStoragestraight to the ternary operator (l = window.localStorage ? localStorage : 0), or better yet, use ||:

  1. w3fools– 你似乎认为 w3schools 与 w3c 相关 – 他们不是。

  2. 使用window.localStorage. 没有window,您将ReferenceError在不支持localStorage.

  3. 不要使用localStorage !== null. 在不支持的浏览器中,localStorage将是undefined,不是null。更好的运算符是!= null,但我根本不会使用比较运算符。您可以直接传递window.localStorage给三元运算符 ( l = window.localStorage ? localStorage : 0),或者更好的是,使用||

var l = window.localStorage || 0;

Edit:Really, this is all you need:

编辑:真的,这就是你所需要的:

if (window.localStorage) {
    // do stuff with localStorage
    // no need to use window anymore
}

回答by Jerodev

You could use Modernizrto check this.

您可以使用Modernizr来检查这一点。

Just like in the answer here: How to detect if browser supports HTML5 Local Storage

就像这里的答案一样: 如何检测浏览器是否支持 HTML5 本地存储

回答by Marco Bonelli

Sometimes browsers block the access to the localStorage, like when you are browsing in incognito mode or private mode and so on... So checking if the storage exists is not the best idea, because sometimes it exists, but is not accessible.

有时浏览器会阻止对 localStorage 的访问,例如当您以隐身模式或私人模式浏览时等等......因此检查存储是否存在不是最好的主意,因为有时它存在,但无法访问。

You can use this function:

您可以使用此功能:

function storageON() {
    try {
        localStorage.setItem("__test", "data");
    } catch (e) {
        return false;
    } 
    return true;
}

if (storageON()) { /* DO SOMETHING */ }