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


当前回答

清除sessionStorage

sessionStorage.clear();

其他回答

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:

localStorage.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);
    }
  }
};

这里的代码给出了一个不想删除的键字符串列表,然后从本地存储中的所有键中筛选这些键,然后删除其他键。

const allKeys = Object.keys(localStorage);

const toBeDeleted = allKeys.filter(value => {
  return !this.doNotDeleteList.includes(value);
});

toBeDeleted.forEach(value => {
  localStorage.removeItem(value);
});