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.
getItem() : This is how you get items from localStorage. removeItem() : Remove an item by key from localStorage. clear() : Clear all localStorage. key() : Passed a number to retrieve the key of a localStorage.
The clear() method removes all the Storage Object item for this domain. The clear() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.
Local Storage data will not get cleared even if you close the browser. Because it's stored on your browser cache in your machine. Local Storage data will only be cleared when you clear the browser cache using Control + Shift + Delete or Command + Shift + Delete (Mac)
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()
.
clear()
clears everything on the current origin (https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript). Using clear()
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
or file:///C:\
). Therefore, it will be fine to use clear()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With