user9592234
user9592234

Reputation:

How to remove Local Storage after certain amount of time?

How can I remove the local Storage data after 2 hours from the time of browser closed?

Upvotes: 0

Views: 7054

Answers (2)

subindas pm
subindas pm

Reputation: 2784

Please try this method

jQuery("document").ready(function($){      
        var Lastclear = localStorage.getItem('Lastclear'),
            Time_now  = (new Date()).getTime();
        //.getTime() returns milliseconds so 1000 * 60 * 60 * 24 = 24 Hours
        if ((time_now - lastclear) > 1000 * 60 * 60 * 5) {
          localStorage.removeItem('HideWelcomeMat{{ name }}');
          localStorage.setItem('Lastclear', Time_now);
        }
      });

Upvotes: -1

Katherine R
Katherine R

Reputation: 1158

Session storage is the best way to clear stored data based on browser close; otherwise, the client cannot react to a browser close event (even web and service workers need the browser running for background processes to occur).

An alternative would be to store an expiration time in local storage as well; however, this would mean you need to (1) update the expiration each time a user does an action which could be heavy on the user (2) check for local storage expiration on page loads/ on events.

Lastly, you can create a cookie with an expiration (such as in this example); however, the expiration will be from the cookie set time and not from the "browser window close time."

Upvotes: 2

Related Questions