有没有办法用javascript重置/清除浏览器的localStorage?


当前回答

清除sessionStorage

sessionStorage.clear();

其他回答

清除sessionStorage

sessionStorage.clear();

这里有一个函数,允许您删除所有localStorage项,但有例外。这个函数需要jQuery。你可以下载要点。

你可以这样称呼它

let clearStorageExcept = function(exceptions) {
  let keys = [];
  exceptions = [].concat(exceptions); // prevent undefined

  // get storage keys
  $.each(localStorage, (key) => {
    keys.push(key);
  });

  // loop through keys
  for (let i = 0; i < keys.length; i++) {
    let key = keys[i];
    let deleteItem = true;

    // check if key excluded
    for (let j = 0; j < exceptions.length; j++) {
      let exception = exceptions[j];
      if (key == exception) {
        deleteItem = false;
      }
    }

    // delete key
    if (deleteItem) {
      localStorage.removeItem(key);
    }
  }
};
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;
                }
            });

如果要从用户的本地存储中删除特定项或变量,可以使用

localStorage.removeItem("name of localStorage variable you want to remove");
window.localStorage.clear(); //try this to clear all local storage