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