Apparently it is not possible to set expiration for data in localStorage
.
Constant storage usage
Generally you will get a finite set of stored items and will update them as needed, keeping usage more or less constant. In this scenario, you would not have to worry about the limit.
Solution to simulate data expiration
If you want to check if the data is old, the best you can do is store the date and time you created them, and when to retrieve them, check if they are within the 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);
Sample source: answer in StackOverflow.com
Removing items that are no longer used
Problems begin if you're just adding new items indiscriminately.
If you know that any item will no longer be used, you can use localStorage.removeItem(key)
to free the storage space.
In addition, 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 old ones .
Temporary storage using sessionStorage
If the scope of stored items does not have to persist when the user closes the tab or the browser you can also use sessionStorage
". It has the same interface as the localStorage
, however, according to the specification, the data is removed after the user exits the browser "session" or "context."
Here is an example usage:
//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;
Sample source here .