Using Vanilla Javascript, I need to write a script that console logs an array of every unique page path visited during a browser session.
Here is my starting point:
function() {
var pageUrl = window.location.href;
return pageUrl;
}
Using Vanilla Javascript, I need to write a script that console logs an array of every unique page path visited during a browser session.
Here is my starting point:
function() {
var pageUrl = window.location.href;
return pageUrl;
}
Session storage is a small (often 5MB) area of space on the user's computer which you can write to. When the session ends (e.g. the browser is closed) the session storage is cleared, and in this way it is different to local storage.
Lets imagine we keep a list of pages around in the session storage. Items are stored in session storage as key / value pairs of strings, and as such we need a key (think of this as a variable name that persists across pages) and a value. Initially, you may think that we can just store an array in such a data store, but the session storage API can only store strings. Therefore, we'll need to convert our array back and forward between a JSON representation as we use it.
When you need to get the list of pages, just grab it from session storage (it's important you get a fresh copy each time, as this accounts for e.g. visits in another tab while the current one remained open). You can do this like so:
function getListOfPages() {
let pages = [];
// If not null, then we have previously stored something --- load that in
if (sessionStorage.getItem("visited") != null) {
// Get the item, and convert it from a JSON string to an actual array
pages = JSON.parse(sessionStorage.getItem("visited"));
}
return pages;
}
And when we need to add a new page, we can then just update that list in storage. For example, we could use a function such as this one:
function addPageToList() {
// Use the get function we made before to get the most up-to-date list of pages
let pages = getListOfPages();
// Add the current page to the list
pages.push(window.location.href);
// Override the value stored in session storage, or add it if no such value exists
sessionStorage.setItem("visited", JSON.stringify(pages));
}
In your post, you mention you want to console.log
all of the unique paths. To do this, you could replace the array in all of the above code with a set, as sets cannot contain duplicate items. However, do note that you can't convert a set to JSON (at least not directly / intuitively), so you may be best advised to do this step after obtaining the list of pages, e.g:
console.log(new Set(getListOfPages()));
Wrapping in a set will remove all of the duplicate items in the array, and then you can print out the set to the console as normal.