12

Should I use clear() to obliterate everything in localStorage, or should I just manually removeItem() the ones I've set on that particular site (which is easy enough to keep track of)?

I ask because I don't want to end up wiping out users' localStorage if they have other values set. I'm testing this in localhost and noticed that by using clear(), everything I'd set previously in other projects was wiped out.

EDIT: I should have mentioned that I know localStorage is domain-locked. I'm running a site that follows this structure:

public-html
(localStorage)
--project1
----files
--project2
----files
--project3
----files

Where each file uses it's own separate localStorage variables. If I localstorage.clear() inside project2, project1 and project3's settings will be lost as well.

4

3 回答 3

12

localstorage 键控到源。因此,如果您的所有项目都在 localhost 上运行,那么您将在使用时擦除所有值clear(),唯一安全的方法是单独删除。

在生产环境中,每个项目都应该有自己的域并且clear应该是安全的。

所以这是一个知道当前原点上还有什么的问题。如果您控制当前原点上的所有内容并且不介意将其全部擦除,那么这clear()是最佳选择,并且专为此目的而设计。如果您的代码的其他部分使用本地存储或托管在同一源上的其他项目,那么您将希望更有选择性并使用removeItem().

于 2013-03-18T20:48:28.760 回答
5

clear()清除当前来源的所有内容(https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript)。在 example.com 上使用clear()不会影响 example2.com 的 localStorage。它正在清除您计算机上所有项目的数据,因为您拥有的所有测试文件都位于同一来源(http://localhostfile:///C:\)。因此,使用它会很好clear()

于 2013-03-18T20:47:58.027 回答
0

Clear() Method

  1. 将清除本地存储中的所有内容
  2. 不接受任何争论

removeItem() 方法

  1. 只会删除您作为参数引用的那些 localStorage 项目。
  2. 要使removeItem工作,您必须需要传入一个参数。例如:

removeItem("list") 只会删除这个 "list" 关键项目

//为了更好地理解下面的代码

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="clear-method">Clear Method</button>
    <button id="removeItem-method">RemoveItem Method</button>


    <script>
        const clearMethod = document.getElementById("clear-method");
        const removeItemMethod = document.getElementById("removeItem-method");

        // declaring arraay for localStorage
        const computer = [
    {
        Brand: "Asus",
        Model: "Unknown"
    }
];

const phone = [
    {
        Brand: "Realme",
        Model: "Unknown"
    }
]

// setting up items on localStorage
localStorage.setItem("computer", JSON.stringify(computer));
localStorage.setItem("phone", JSON.stringify(phone));

        clearMethod.addEventListener("click", ()=>{
        localStorage.clear();
        })

        removeItemMethod.addEventListener("click", ()=>{
            localStorage.removeItem("phone");
        })
    </script>
   
</body>
</html>

于 2021-08-10T17:15:52.630 回答