When will items in HTML5 local storage expire?

How long can data stored in localStorage (as part of DOM storage in HTML 5) be used? Can I set the expiration time for the data put into localStorage?

#1 building

// Functions
function removeHtmlStorage(name) {
    localStorage.removeItem(name);
    localStorage.removeItem(name+'_time');
}

function setHtmlStorage(name, value, expires) {

    if (expires==undefined || expires=='null') { var expires = 3600; } // default: 1h

    var date = new Date();
    var schedule = Math.round((date.setSeconds(date.getSeconds()+expires))/1000);

    localStorage.setItem(name, value);
    localStorage.setItem(name+'_time', schedule);
}

function statusHtmlStorage(name) {

    var date = new Date();
    var current = Math.round(+date/1000);

    // Get Schedule
    var stored_time = localStorage.getItem(name+'_time');
    if (stored_time==undefined || stored_time=='null') { var stored_time = 0; }

    // Expired
    if (stored_time < current) {

        // Remove
        removeHtmlStorage(name);

        return 0;

    } else {

        return 1;
    }
}

// Status
var cache_status = statusHtmlStorage('cache_name');

// Has Data
if (cache_status == 1) {

    // Get Cache
    var data = localStorage.getItem('cache_name');
    alert(data);

// Expired or Empty Cache
} else {

    // Get Data
    var data = 'Pay in cash :)';
    alert(data);

    // Set Cache (30 seconds)
    if (cache) { setHtmlStorage('cache_name', data, 30); }

}

#2 building

Although the local store does not provide an expiration mechanism, the cookie does. Simply pairing the local store key with the cookie provides an easy way to ensure that the local store can be updated with the same expiration parameters as the cookie.

Example in jQuery:

if (!$.cookie('your_key') || !localStorage.getItem('your_key')) {
    //get your_data from server, then...
    localStorage.setItem('your_key', 'your_data' );
    $.cookie('your_key', 1);
} else {
    var your_data = localStorage.getItem('your_key');
}
// do stuff with your_data

This example sets cookie s that use the default parameters to expire when the browser is closed. Therefore, when the browser is closed and reopened, your data's local data store will be refreshed through a server-side call.

Note that this is not exactly the same as deleting the local data store, but updating the local data store when the cookie expires. However, if your primary goal is to be able to store more than 4K clients (the limit of cookie size), pairing this pair of cookies with local storage will help you achieve a larger storage size using the same expiration parameters as cookies.

#3 building

Solutions using angular and localforge:

angular.module('app').service('cacheService', function() {

  return {
    set: function(key, value, expireTimeInSeconds) {
      return localforage.setItem(key, {
        data: value,
        timestamp: new Date().getTime(),
        expireTimeInMilliseconds: expireTimeInSeconds * 1000
      })
    },
    get: function(key) {
      return localforage.getItem(key).then(function(item) {
        if(!item || new Date().getTime() > (item.timestamp + item.expireTimeInMilliseconds)) {
          return null
        } else {
          return item.data
        }
      })
    }
  }

})

#4 building

Cannot specify expiration time. It all depends on the user.

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/localStorage

Of course, some of the content your application stores on the client may not appear in the future. Users can explicitly get rid of local storage, otherwise the browser may encounter space problems. Defensive programming is a good thing. But, in general, according to some practical definitions of the word, things will last forever.

Edit - obviously, if you think your applications are too old, you can actively delete them. That is, you can explicitly include a timestamp in the saved content, and then use that timestamp later to determine whether the information should be refreshed.

#5 building

The lifecycle is controlled by the application / user.

from standard :

The user agent should expire data in the local store only for security reasons or when requested by the user. User agents should always avoid deleting data when running scripts that have access to that data.

Tags: angular JQuery Programming

Posted on Thu, 19 Mar 2020 05:14:21 -0700 by Gokul