Search code examples
javascripthtmlweb-storage

Is it possible to access a "stored date" (metadata) of a localstorage item?


I am working on a web app where I use localstorage to store in-progress data for incomplete activities. I would like to display when last an incomplete activity was updated. It would be possible to add a "storedDate" (or similar) field to the items I store and update it whenever the data is updated, but I would rather use a "stored date" meta (if there is any available) for a more generic approach.

I have looked at all the HTML5 web storage API references that I could find, but have not been able to find any relating to metadata available on localstorage items (if any). Is anything available? Does anyone have documentation I could look at to access the metadata?


Solution

  • Local Storage is a simple key-value storage, where is the "value" is always a string. You can store a JSON object, but you have to stringify it.

    Example:

    var objToStore = {
      my_date: Date.now(),
      any_data: "SUPER TEXT"
    };
    
    localStorage['my_value'] = JSON.stringify(objToStore); 
    

    If you need to read and parse it:

    var readValue;
    try {
      readValue = JSON.parse(localStorage['my_value'])
    } catch(e) {
      // parse error
    }