简体   繁体   中英

localStorage.clear() usage

localStorage.clear() seems to behave in a manner that completely wipes all local storage. Local Storage seems to fit my use case, but I'm concerned of the possibility the local storage isn't guaranteed to not be cleared outside of my control.

For example:

My web site has a line of code:

localStorage.setItem('some', 'data');

Some other website that is operating in the same browser on another tab has this line of code:

localStorage.clear();

If that scenario ever happens, when I go to access localStorage.getItem('some'); , it will return null because someone else ran localStorage.clear() .

  1. Should we never run localStorage.clear() ?
  2. What is the proper usage of localStorage.clear() if I am heavily using local storage and don't want to write a ton of code to remove items from the local storage individually localStorage.removeItem('item1'); localStorage.removeItem('item2'); // etc... localStorage.removeItem('item1'); localStorage.removeItem('item2'); // etc...
  3. Is there some way to prevent items from being removed if someone runs localStorage.clear() somewhere else?

There is no need to worry, every time you open a new window or tab a new session is created and localStorage refers to the local session of that tab/window which is unique for that domain.

  1. Your fine running it, it will only clear your variables

  2. If you need to clear everything use feel free to use localStorage.clear()

  3. Someone else cannot clear your local storage

https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API

It is unique per domain. For example the localStorage for your domain

protocol://abc.com will be different from protocol://xyz.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM