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 useremoveItem()
.clear()
clears everything on the current origin (https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript). Usingclear()
on example.com will not affect the localStorage for example2.com. It is clearing data for all projects on your computer because all of the testing files that you have are on the same origin (http://localhost
orfile:///C:\
). Therefore, it will be fine to useclear()