如何从多个过去的页面 JavaScript 中获取字符串 URL

问题描述

我对 JavaScript 非常陌生。我正在尝试制作一个 Web 应用程序,其中一个简单的后退按钮将转到我正在查找的特定页面,其中包含“搜索”一词。我不知道确切的 URL,因为该 URL 中的参数会发生变化,我需要使其与用户想要的保持一致。但是这个按钮应该回到那个页面,而不管点击了其他链接。 例如: 如果我点击

Home Page
Main Page
Page 1
Page 1.3
Back

我希望返回总是带我到主页,并使用它之前的确切参数,而不是主页。

我尝试了以下方法: 按钮本身

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

但这会将我带到第一个主页。我以为 document.referrer 会让我得到过去的 URL,但它似乎对我不起作用。有没有办法从过去的页面获取 URL?因此,如果我在第 2 页上,我可以获取所有 URL 并搜索主页吗?非常感谢任何帮助!

我也是 Stack Overflow 的新手,所以如果有任何说明,请随时告诉我!

解决方法

document.referrer 并非在所有情况下都与实际 URL 相同。

最好的办法是将 URL 存储在 sessionStorage 中。

将此代码段添加到您的页面:

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

这是你的 goBackHelper() 函数:

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

了解 document.referrer here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...