localStorage - clear()或removeItem()? [英] localStorage - clear() or removeItem()?

查看:325
本文介绍了localStorage - clear()或removeItem()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该使用 clear()来删除 localStorage 中的所有内容,还是应该手动 removeItem()我在那个特定网站上设置的那个(这很容易跟踪)?



我问因为如果设置了其他值,我不想最终消除用户的 localStorage 。我在localhost中测试了这个,并注意到通过使用 clear(),我之前在其他项目中设置的所有内容都被删除了。



编辑:我应该提到我知道localStorage是域锁定的。我正在运行一个遵循这种结构的网站:

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

每个文件使用它自己独立的localStorage变量。如果我在project2中 localstorage.clear(),那么project1和project3的设置也会丢失。

解决方案

localstorage是一个原点。因此,如果您的所有项目都在localhost上运行,那么当您使用 clear()时,您将擦除所有值,并且唯一安全的方法是单独删除。 / p>

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



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


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.

解决方案

localstorage is keyed to an origin. So if all of your projects are running on localhost, then you'll wipe all of your values when you use clear(), and the only safe method is individual removal.

In a production environment, each project should have its own domain and clear should be safe.

So it's a question of knowing what else is on the current origin. If you control everything on the current origin and don't mind wiping it all, clear() is the best choice and was designed for that purpose. If there are other parts of your code using localstorage or other projects hosted on the same origin then you will want to be more selective and use removeItem().

这篇关于localStorage - clear()或removeItem()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆