Javascript localStorage 不适用于谷歌浏览器

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

localStorage is not working on google chrome

javascriptjqueryhtmlgoogle-chromefirefox

提问by Tushar

I am using browsers localStorageto store a value, but while using google chrome, when we refresh the page using window.location.reload(), localStorage.valueis flushed. e.g

我正在使用浏览器localStorage来存储一个值,但是在使用谷歌浏览器时,当我们使用 刷新页面时window.location.reload(),会localStorage.value被刷新。例如

localStorage.value1=true

after reloading, i am not getting this value1 object in localStorage.

重新加载后,我没有在 localStorage 中获得这个 value1 对象。

Same code works on mozila firefox, but not in chrome. While using firefox, localstorage value is persistent.

相同的代码适用于 mozila firefox,但不适用于 chrome。使用 firefox 时,localstorage 值是持久的。

回答by Shankar

LocalStorage supports only string values, not boolean or others.

LocalStorage 仅支持字符串值,不支持布尔值或其他值。

Method to store and retrieve values:

存储和检索值的方法:

Put the value into storage

将价值存入

localStorage.setItem('value1', 'true');

Retrieve the value from storage

从存储中检索值

var val1 = localStorage.getItem('value1');

Read more on MDN..

在 MDN 上阅读更多..

回答by André Dion

You need to use the correct API for Storage:

您需要使用正确的APIStorage

window.localStorage.setItem('value1', 'true');

What you're doing is setting a property on a variable which won't persist between page loads. Firefox is likely being too smart and recognizing that you want to actually save the value in the browser's local storage store.

您正在做的是在一个变量上设置一个属性,该属性不会在页面加载之间持续存在。Firefox 可能太聪明了,并意识到您希望将值实际保存在浏览器的本地存储中。

回答by fba_pereira

Try it

尝试一下

window.localStorage.setItem("value1", true);

var yourvar = window.localStorage.getItem("value1");