有没有办法用javascript重置/清除浏览器的localStorage?
当前回答
window.localStorage.clear(); //try this to clear all local storage
其他回答
如果有人正在寻找在浏览器选项卡关闭时清除localStorage的方法,下面的代码是有效的。(示例用例:将一些复制的数据保存在localStoarge中,以粘贴到另一个选项卡上,但同时,需要缓存在所有以前的选项卡关闭时不显示在新选项卡上)
window.onbeforeunload=()=>{//获取具有指定密钥的localStorage项const storage=JSON.parse(localStorage.getItem('MY_KEY'));//清除缓存(如果存在)if(!isNil(存储))localStorage.removeItem('MY_KEY');};
它将一个eventListener添加到窗口中,以检测选项卡关闭,并在关闭之前清除选项卡的localStorage(指定键)。它不会清除其他选项卡上的localStorage(相同密钥)。
这是一个很好的解决方案,如果我们想只在关闭的选项卡中清除localStorage,并保持其他选项卡上的localStorage(相同键)不变。
因此
只要用户打开一个选项卡,用户就可以利用localStorage缓存,并且关闭所有选项卡后,localStorage将不会出现在新的选项卡。
window.localStorage.clear(); //try this to clear all local storage
localStorage.clear();
or
window.localStorage.clear();
清除特定项目
window.localStorage.removeItem("item_name");
要按id删除特定值,请执行以下操作:
var item_detail = JSON.parse(localStorage.getItem("key_name")) || [];
$.each(item_detail, function(index, obj){
if (key_id == data('key')) {
item_detail.splice(index,1);
localStorage["key_name"] = JSON.stringify(item_detail);
return false;
}
});
下面是一个简单的代码,它将使用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,则清除本地存储。
如果要清除存储在localStorage中的所有项目,则
localStorage.clear();
使用此选项清除所有存储的密钥。
如果您只想清除/删除特定的键/值,则可以使用removeItem(键)。
localStorage.removeItem('yourKey');