有没有办法用javascript重置/清除浏览器的localStorage?
当前回答
下面是一个简单的代码,它将使用javascript清除存储在浏览器中的本地存储
<script type="text/javascript">
if(localStorage) { // Check if the localStorage object exists
localStorage.clear() //clears the localstorage
} else {
alert("Sorry, no local storage."); //an alert if localstorage is non-existing
}
</script>
要确认本地存储是否为空,请使用以下代码:
<script type="text/javascript">
// Check if the localStorage object exists
if(localStorage) {
alert("Am still here, " + localStorage.getItem("your object name")); //put the object name
} else {
alert("Sorry, i've been deleted ."); //an alert
}
</script>
如果返回null,则清除本地存储。
其他回答
清除sessionStorage
sessionStorage.clear();
如果要从用户的本地存储中删除特定项或变量,可以使用
localStorage.removeItem("name of localStorage variable you want to remove");
如果要清除存储在localStorage中的所有项目,则
localStorage.clear();
使用此选项清除所有存储的密钥。
如果您只想清除/删除特定的键/值,则可以使用removeItem(键)。
localStorage.removeItem('yourKey');
这里的代码给出了一个不想删除的键字符串列表,然后从本地存储中的所有键中筛选这些键,然后删除其他键。
const allKeys = Object.keys(localStorage);
const toBeDeleted = allKeys.filter(value => {
return !this.doNotDeleteList.includes(value);
});
toBeDeleted.forEach(value => {
localStorage.removeItem(value);
});
使用此选项清除localStorage:
localStorage.clear();
推荐文章
- 在Redux应用程序中哪里写localStorage ?
- 如何在ReactJS中从“外部”访问组件方法?
- 为时刻添加持续时间(moment.js)
- 如何在JavaScript中获得时区名称?
- 在JSON键名中哪些字符是有效的/无效的?
- jQuery中的live()转换为on()
- 如何区分鼠标的“点击”和“拖动”
- IE9是否支持console.log,它是一个真实的功能吗?
- Node.js同步执行系统命令
- 如何转义JSON字符串包含换行字符使用JavaScript?
- jQuery等价于JavaScript的addEventListener方法
- jQuery需要避免的陷阱
- JavaScript中变量字符串的XML解析
- 'React'指的是一个UMD全局,但当前文件是一个模块
- 为什么useState不触发重新渲染?