Apparently it is not possible to set expiration for data in localStorage
.
Constant use of storage
Usually you will have a finite set of stored items and will update them when necessary, keeping the use more or less constant. In this scenario, you wouldn’t have to worry about the limit.
Solution to simulate data expiration
If you want to check whether the data is old, the best you can do is to store the date and time you created it and, when to retrieve it, check whether it is within acceptable time.
Example:
var object = {value: "value", timestamp: new Date().getTime()}
localStorage.setItem("key", JSON.stringify(object));
Then retrieve the item and check the date:
var object = JSON.parse(localStorage.getItem("key")),
timestamp = object.timestamp,
value = object.value;
verificarValidade(timestamp);
Example source: response in Stackoverflow.com
Removing items that are no longer used
Problems start if you’re just adding new items indiscriminately.
If you know that some item will no longer be used, you can use the localStorage.removeItem(key)
to free up storage space.
Also, if you have stored the date as indicated in the previous topic, you can also iterate over the stored items using length
and key(n)
and remove the old.
Temporary storage using sessionStorage
If the scope of the stored items does not need to last when the user closes the tab or the browser can also use the sessionStorage
. He owns the same interface of localStorage
, however, according to the specification, the data is removed after the user terminates the "session" or "context" of the browser.
Follow an example of use:
//save a value
sessionStorage.setItem("name", "Seu nome");
//retrieve item
var name = sessionStorage.getItem("name");
//get the key name for the first item
var key = sessionStorage.key(0);
//remove the key
sessionStorage.removeItem(key);
//check how many key-value pairs are present
var count = sessionStorage.length;
Example source here.
So it means that I can not go putting whatever you want in the localstorage... how do I know then if it is full?
– Miguel Angelo
@Miguelangelo In theory, you shouldn’t just go adding infinitely things to Localstorage. Usually you will want to update these items there for example. On the other hand, if you know that some item will no longer be used, you can use the
localStorage.removeItem(key);
to remove and release space.– utluiz
@Miguelangelo I updated the answer with a few more ideas.
– utluiz
Researching a little more, I came to the knowledge of
sessionstorage
, which expires at the close of the browser window/tab. In my case specifically, this was the best solution... put an addendum there in your reply on sessionstorage, which will be quite complete.– Miguel Angelo
@Miguelangelo Thanks for the tip. I reworked the answer completely. If the
sessionStorage
meet what you need will be much easier to handle data volume.– utluiz