How to update array with same key in Session Storage

Puzzled Boy picture Puzzled Boy · May 10, 2015 · Viewed 9.9k times · Source

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);
    }
}

Answer

user3459110 picture user3459110 · May 10, 2015

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.