簡體   English   中英

如何從多個過去的頁面中獲取字符串 URL JavaScript

[英]How to get string URL from multiple past pages JavaScript

我對 JavaScript 很陌生。 我正在嘗試制作一個 web 應用程序,其中一個簡單的后退按鈕將 go 到我正在尋找的特定頁面,其中包含“搜索”一詞。 我不知道確切的 URL,因為 URL 中的參數發生了變化,我需要使其與用戶想要的保持一致。 但是這個按鈕應該 go 回到那一頁,不管點擊了其他鏈接。 例如:如果我點擊

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:

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的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM