How to auto expire local storage values in angular js?

19,238

Solution 1

I wrote an extension for angular-localStorage (https://github.com/grevory/angular-local-storage) that is able to delete entries in localStorage automatically when you provide an optional parameter in the set method.

https://gist.github.com/Kyoss79/8cd37a54679804fdeb6d

Solution 2

after bootstraping your module call run and setup an $interval that clears local storage after 20 minutes.

app.run(function($interval){
  $interval(() => {
    delete localStorage[key]
    // delete all the required localStorage variables by specifying their keys
  }, 1000*60*20)
})

Solution 3

According to W3Schools:

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

However, a similar question has already been asked and answered elsewhere: When do items in HTML5 local storage expire? There were some workarounds mentioned there that may be of use to you.

Share:
19,238

Related videos on Youtube

Janani
Author by

Janani

Updated on June 04, 2022

Comments

  • Janani
    Janani about 2 years

    I am using localStorage in my application. I want to clear those values after 20 minutes. Can u please help me out?

  • Elger Mensonides
    Elger Mensonides over 8 years
    Works great thanks! Should be part of the library. Maybe you could contribute?
  • JsAndDotNet
    JsAndDotNet over 8 years
    @Kyoss Am i right in thinking this adds an expiry time so you can query localstorage and remove the row if it's too old? I can't see anything that expires the row automatically? Neat addition. Would defintiely be worth having in the core lib. :)
  • Anil Dukkipatty
    Anil Dukkipatty almost 6 years
    @HarryBosh yes. The page would need to be open for this to work. We would have to store the data along with an expiry timestamp to validate it otherwise. This timestamp can be used while fetching the data and the function being used for this can delete the data and return null if it has expired. Hope this helps :)
  • Harry Bosh
    Harry Bosh almost 6 years
    you cant really 'auto expire' if the page needs to be open
  • Anil Dukkipatty
    Anil Dukkipatty almost 6 years
    @HarryBosh that's correct you can't auto expire directly. You can use the workaround mentioned in the above comment.