0

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

  • 3
    Possible duplicate of [How can I remove local storage after one hour?](https://stackoverflow.com/questions/45561610/how-can-i-remove-local-storage-after-one-hour) – Carsten Løvbo Andersen Mar 27 '19 at 10:27
  • Sir, but I want to remove storage after the browser is closed. Is there any possible way to do that –  Mar 27 '19 at 10:31
  • Possible duplicate of [How to delete a localStorage item when the browser window/tab is closed?](https://stackoverflow.com/questions/9943220/how-to-delete-a-localstorage-item-when-the-browser-window-tab-is-closed) – Shubham Baranwal Mar 27 '19 at 11:00
  • Sir, but I want to remove the local Storage data after 2 hours from the time of browser closed –  Mar 27 '19 at 11:03

2 Answers2

2

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

Katherine R
  • 1,107
  • 10
  • 20
  • Is there any best way to store user logged in session data using jquery without using any server side language? –  Mar 27 '19 at 11:41
  • Session storage acts just like local storage (both are client-side); however, it clears on browser close automatically. The last alternative would be cookies -- there is a jquery plugin talked about here https://stackoverflow.com/a/1458728/6322587 that you could use – Katherine R Mar 27 '19 at 11:43
  • Can we clear cookies after few hours from the time of browser closed –  Mar 27 '19 at 11:57
  • I updated the post with a comment on the cookie with expiration – Katherine R Mar 27 '19 at 13:52
-1

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);
        }
      });
subindas pm
  • 2,668
  • 25
  • 18