Javascript 在javascript中清除localStorage?

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

Clearing localStorage in javascript?

javascriptlocal-storage

提问by Bnicholas

Is there any way to reset/clear browser's localStorage in javascript?

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

回答by Digital Plane

Use this to clear localStorage:

使用它来清除 localStorage:

localStorage.clear();

回答by Ajeet Lakhani

If you want to remove a specific Item or variable from the user's local storage, you can use

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

localStorage.removeItem("name of localStorage variable you want to remove");

回答by Naftali aka Neal

window.localStorage.clear(); //try this to clear all local storage

回答by Christian Juth

Here is a function that will allow you to remove all localStorage items with exceptions. You will need jQueryfor this function. You can download the gist.

这是一个允许您删除所有 localStorage 项目但有异常的功能。您将需要jQuery来实现此功能。您可以下载要点

You can call it like this

你可以这样称呼

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

回答by Willem van der Veen

Localstorage is attached on the global window. When we log localstorage in the chrome devtools we see that it has the following APIs:

Localstorage 附加在全局window. 当我们在 chrome devtools 中记录 localstorage 时,我们看到它具有以下 API:

enter image description here

在此处输入图片说明

We can use the following API's for deleting items:

我们可以使用以下 API 来删除项目:

  1. localStorage.clear(): Clears the whole localstorage
  2. localStorage.removeItem('myItem'): To remove individual items
  1. localStorage.clear(): 清除整个本地存储
  2. localStorage.removeItem('myItem'):删除单个项目

回答by Hyman Giffin

First things first, you need to check to make sure that localStorage is enabled. I would recommend doing it like this:

首先,您需要检查以确保启用了 localStorage。我建议这样做:

var localStorageEnabled = false;
try { localStorageEnabled = !!localStorage; } catch(e) {};

Yes, you can (in some cases) just check to see if the localStorage is a member of the window object. However, there are iframe sandboxing options (among other things) that will throw an exception if you even attempt to access the index 'localStorage'. Thus, for best-practices reasons, this is the best way to check to see if the localStorage is enabled. Then, you can just clear the localStorage like so.

是的,您可以(在某些情况下)只检查 localStorage 是否是 window 对象的成员。但是,如果您甚至尝试访问索引“localStorage”,也有 iframe 沙盒选项(除其他外)会引发异常。因此,出于最佳实践的原因,这是检查是否启用 localStorage 的最佳方法。然后,您可以像这样清除 localStorage 。

if (localStorageEnabled) localStorage.clear();

For example, you could clear the localStorage after an error occurs in webkit browsers like so.

例如,您可以像这样在 webkit 浏览器中发生错误后清除 localStorage。

// clears the local storage upon error
if (localStorageEnabled)
  window.onerror = localStorage.clear.bind(localStorage);

In the above example, you need the .bind(window)because without it, the localStorage.clearfunction will run in the context of the windowobject, instead of the localStorageobject making it silently fail. To demonstrate this, look at the below example:

在上面的示例中,您需要 ,.bind(window)因为没有它,localStorage.clear函数将在window对象的上下文中运行,而不是localStorage对象使其静默失败。为了证明这一点,请看下面的例子:

window.onerror = localStorage.clear;

is the same as:

是相同的:

window.onerror = function(){
    localStorage.clear.call(window);
}

回答by Moshiur Rahman

If you want to clear all item you stored in localStoragethen

如果要清除存储在localStorage 中的所有项目,则

localStorage.clear();

Use this for clear all stored key.

用于清除所有存储的密钥。

If you want to clear/remove only specific key/value then you can use removeItem(key).

如果您只想清除/删除特定的键/值,则可以使用removeItem(key)

localStorage.removeItem('yourKey');

回答by vino

localStorage.clear();

or

或者

window.localStorage.clear();

to clear particular item

清除特定项目

window.localStorage.removeItem("item_name");

To remove particular value by id :

要按 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;
                }
            });

回答by m-farhan

To clear sessionStorage

清除 sessionStorage

sessionStorage.clear();

回答by amaroko

Here is a simple code that will clear localstorage stored in your browser by using javascript

这是一个简单的代码,它将使用 javascript 清除存储在浏览器中的 localstorage

    <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>

To confirm if localstorage is empty use this code:

要确认 localstorage 是否为空,请使用以下代码:

<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>

if it returns null then your localstorage is cleared.

如果它返回 null 则你的本地存储被清除。