Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Storage with Expiration

How can I set an expiration time on a specific local storage variable?

Example: If I have a page disclaimer and once the user clicks "accept" I store a certain variable in the local storage. However after 12 hours, I want it to get deleted and ask the user to accept again.

I don't want to store the variable in session storage, because the disclaimer will prompt every time the user opens a new tab.

Cookies would be another solution, but I rather not use it if possible.

Thanks!

like image 638
LuVu Avatar asked Dec 05 '18 17:12

LuVu


People also ask

Does localStorage store data with expiration date?

The localStorage object stores data with no expiration date. The data is not deleted when the browser is closed, and are available for future sessions.

How do I set localStorage timeout?

If you're familiar with the browsers localStorage object, you know that there's no provision for providing an expiry time. However, we can use Javascript to add a TTL (Time to live) to invalidate items in localStorage after a certain period of time elapses.

How long local storage objects can store the data?

HTML Web Storage Objects window.localStorage - stores data with no expiration date. window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

Does session storage expire?

sessionStorage is similar to localStorage ; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.


2 Answers

There's no built-in way to expire values in storage. One solution is to store a timestamp, then in each visit compare the stored time (if there is one) against the local time to determine if the value has expired. Example:

const expirationDuration = 1000 * 60 * 60 * 12; // 12 hours

const prevAccepted = localStorage.getItem("accepted");
const currentTime = new Date().getTime();

const notAccepted = prevAccepted == undefined;
const prevAcceptedExpired = prevAccepted != undefined && currentTime - prevAccepted > expirationDuration;
if (notAccepted || prevAcceptedExpired) {
  alert("Disclaimer: ...");
  localStorage.setItem("accepted", currentTime);
}
like image 58
Aaron Beall Avatar answered Oct 01 '22 07:10

Aaron Beall


I strongly recommend the usage of lscache. Just include this 2.5kb JS into your APP or per CDN. Its highly configurable and usage its pretty easy. It supports strings or objects.

If (lscache.get('myVar') === null) {
  alert('time exceeded')
  //set variable which will expire in 3 days
  lscache.set('myVar', true, (60*24*3))
}
like image 30
TefoD Avatar answered Oct 01 '22 07:10

TefoD