How to update array with same key in Session Storage

11,184

Solution 1

The sessionStorage object is not an array. It is an instance of the native Storage constructor which persists data on page navigation. And you can have only one value for each key. Your best bet will be to namespace the history in the session under a history key and store a JSON array under that key.

Here is an example:

window.addEventListener('load', function recordInHistory() {
  var current = sessionStorage.getItem('history');
  if (!current) { // check if an item is already registered
    current = []; // if not, we initiate an empty array
  } else {
    current = JSON.parse(current); // else parse whatever is in
  }
  current.push({
    title: document.title,
    url: window.location.href
  }); // add the item
  sessionStorage.setItem('history', JSON.stringify(current)); // replace
});

To retrieve the history, of-course JSON.parse(sessionStorage.getItem('history')) will work.

Solution 2

The first parameter of setItem is a key, you can append a random number or Date.now() or a counter++ value to make it unique.

if (window.sessionStorage) {
    var currentTite = document.title;
    var currentURL = window.location.href;
    sessionStorage.setItem(currentTite + ':' + Date.now().toString(), currentURL);

    for (i = 0; i <= sessionStorage.length - 1; i++) {
        key = sessionStorage.key(i);
        console.log(key);
        val = sessionStorage.getItem(key);
        console.log(val);
    }
}

Solution 3

It depends on how you want to process the data afterwards. Anyway, as sessionStorage is a key-value storage, you can't hold different values with the same keys and you can't have duplicate key-value pairs in the storage.

As an option, you can store an array of user's history, represented by objects ({ title: document.title, url: window.location.href }). The code will look something like this:

var UserHistory = {
   key: 'userHistory',
   push: function() {
      var cur = JSON.parse(sessionStorage.getItem(UserHistory.key)) || [];
      cur.push({ title: document.title, url: window.location.href });
      sessionStorage.setItem(UserHistory.key, JSON.stringify(cur));
   },
   get: function() {
      return JSON.parse(sessionStorage.getItem(UserHistory.key));
   }
}
UserHistory.get(); // null
UserHistory.push();
UserHistory.get(); // [ Object ]
Share:
11,184

Related videos on Youtube

Naresh
Author by

Naresh

profile for Puzzled Boy on Stack Exchange, a network of free, community-driven Q&amp;A sites http://stackexchange.com/users/flair/2100519.png

Updated on September 15, 2022

Comments

  • Naresh
    Naresh over 1 year

    I am trying to store pages visited history in Session-storage. Session storage is working how I want.

    Problem: When I visit a 1st, 2nd, 3rd, & 4th page and then visit the 2nd page and 3rd page again, it does not update the array again with the 2nd and 3rd page.

    Not appending data in array 2nd and 3rd page, these already exist but I visit these pages again then it should be added in the array.

    I want to store every page visited in history in the array.

    if (window.sessionStorage) {
        var currentTite = document.title;
        var currentURL = window.location.href;
        sessionStorage.setItem(currentTite, currentURL);
        //var storedData = sessionStorage.getItem(currentTite);
    
        for (i = 0; i <= sessionStorage.length - 1; i++) {
            key = sessionStorage.key(i);
            console.log(key);
            val = sessionStorage.getItem(key);
            console.log(val);
        }
    }
    
  • Naresh
    Naresh almost 9 years
    how can i get all the detail simply in console ?
  • Naresh
    Naresh almost 9 years
    how can i get all the detail simply in console ?
  • user3459110
    user3459110 almost 9 years
    @PuzzledBoy just use console.log(sessionStorage.getItem('history'));.
  • Mottie
    Mottie almost 9 years
    @PuzzledBoy There is nothing wrong with replacing 'history' with the currentTite variable from your question. I would do that if your javascript code is loaded from an external file and used in multiple pages.
  • Mottie
    Mottie almost 9 years
    Including Date.now() in the sessionStorage key is not a good idea. Every time the user reloads the page, you're creating another set of data. How do you determine which set to load, and which set to delete?
  • Avraam Mavridis
    Avraam Mavridis almost 9 years
    @Mottie you are right, but isnt that the goal of the question? maybe an increment number is more appropriate.
  • Mottie
    Mottie almost 9 years
    Ah, yes, I guess you are right. I don't know why window.history isn't being used.
  • Artyom Neustroev
    Artyom Neustroev almost 9 years
    @PuzzledBoy there is a get method that returns the whole array of data. You then iterate over it.