Search code examples
jquerylocal-storagelocal-variables

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?


Solution

  • 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."