Search code examples
javascriptreferrerhistory.js

How to get string URL from multiple past pages JavaScript


I am very new to JavaScript. I am trying to make a web application, where a simple back button will go to a specific page I am looking for, one that has the word "search" in it. I don't know the exact URL, because the parameters within that URL change, and I need to keep it consistent to what the user wanted. But this one button should go back to that one page, regardless of the other links that were clicked. For example: If I clicked on

Home Page
Main Page
Page 1
Page 1.3
Back

I want the back to always take me to Main Page with the exact parameters it had before, not Home Page.

I tried the following: The button itself

movieTableBodyElement.append('<a href="#" onclick="javascript:goBackHelper();">' + " << Back" + '</a>'); // Building the HTML button, calls the goBackHelper() function
function goBackHelper()
{
    // checks if the page directly behind is the Main Page with "search"
    if(document.referrer.includes("search"))
    {
        // if its the main page, exit the function and end recursive call
        window.history.go(-1);
    }
    else
    {
        // it is not the last page, so go to the past page and check again
        window.history.go(-1);
        goBackFunction();
    }
}

But this takes me to the very first home page. I thought that document.referrer would get me the past URL, but it doesn't seem to be working for me. Is there a way to get the URL from past pages? So if I am on page 2, can I get all the URLs and search for Main Page? Any help is greatly appreciated!

I'm also new to Stack Overflow, so if there is any clarification please don't hesitate to let me know!


Solution

  • document.referrer is not the same as the actual URL in all situations.

    Your best bet is to store the URLs in sessionStorage.

    Add this snippet of code to your pages:

    if (sessionStorage.getItem("locationHistory") !== null) {
        var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
        locationHistoryArray.push(window.location.href);
        sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
    } else {
        var locationHistoryArray = [];
        locationHistoryArray.push(window.location.href);
        sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
    }
    

    And this is your goBackHelper() function :

    function goBackHelper() {
        var searchString = 'search'; //modify this
        var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
        for (i = 0; i < locationHistoryArray.length; i++) {
            if (locationHistoryArray[i].includes(searchString)) {
                window.location.assign(locationHistoryArray[i]);
                break;
            }
        }
    }
    

    Read about document.referrer here.