簡體   English   中英

HTML5歷史記錄 - 返回上一頁的完整頁面按鈕?

[英]HTML5 History - Back button to previous full page?

我正在使用HTML5歷史API來修改URL,因為選擇了某些產品屬性(例如綠色汽車,藍色汽車)以允許深層鏈接共享。

但是,這不是單頁應用程序,所以我不想劫持用戶的后退按鈕:如果他們按下,我想讓他們轉到上一頁,而不是之前的車顏色。

實現這一目標的最佳方法是什么?

示例歷史:

/page1
/page2
/page2?color=green
/page2?color=red
/page2?color=blue

然后按瀏覽器的后退按鈕返回/page1

看起來我應該一直在使用

history.replaceState();

而不是history.pushState(); 它取代了瀏覽器的URL,但沒有添加到歷史對象,因此后退按鈕可以按我的意願工作。

history.replaceState()的運行方式與history.pushState()完全相同,只是replaceState()修改當前歷史記錄條目而不是創建新條目。

developer.mozilla.org

這是一個使用sessionStorage的解決方案,它使您的應用程序能夠轉到以前存儲的頁面,而不會破壞可用性期望/瀏覽器后退按鈕功能。 移動到先前的URL(例如,不同的顏色)是在瀏覽器上為用戶使用后退按鈕的預期結果。

JS

function getCurrentPath() {
    return sessionStorage.getItem("currentPath");
}

function getPreviousPath() {
    return sessionStorage.getItem("previousPath");
}

function setCurrentPath(path) {
    var currentPath = getCurrentPath();
    if (currentPath != path) {
        sessionStorage.setItem("previousPath", currentPath);
        sessionStorage.setItem("currentPath", path);
    } else {
        console.log('Path has not changed: ' + path);
    }
}

function goToPrevious() {
    var previousPath = getPreviousPath();
    if (previousPath && previousPath != 'null') {
        window.location.href = previousPath;
    } else {
        alert('Previous page is not defined.');
    }
}

test1.html

<!DOCTYPE html>
<html>
    <head>
        <title>Test 1</title>
        <meta charset="UTF-8">
        <script src="test.js"></script>
        <script>
            setCurrentPath('test1.html');
            console.log('Current Path:', getCurrentPath());
            console.log('Previous Path:', getPreviousPath());
        </script>
    </head>
    <body>
        <button onclick="goToPrevious();">Go to previous page</button>
        <a href="test2.html">Test 2</a>
        <a href="?color=red">Red</a>
        <a href="?color=green">Green</a>
        <a href="?color=blue">Blue</a>
    </body>
</html>

test2.html

<!DOCTYPE html>
<html>
    <head>
        <title>Test 2</title>
        <meta charset="UTF-8">
        <script src="test.js"></script>
        <script>
            setCurrentPath('test2.html');
            console.log('Current Path:', getCurrentPath());
            console.log('Previous Path:', getPreviousPath());
        </script>
    </head>
    <body>
        <button onclick="goToPrevious();">Go to previous page</button>
        <a href="test1.html">Test 1</a>
        <a href="?color=red">Red</a>
        <a href="?color=green">Green</a>
        <a href="?color=blue">Blue</a>
    </body>
</html>

您可以看到這允許用戶更改查詢字符串參數,但這不會影響通過轉發操作移動到上一頁的功能,只需在路徑之間存儲更改即可。 您可以通過使用數組而不是像我在這里完成的兩個值來擴展它,但如果您希望這樣做,我會將其留下來實現。

暫無
暫無

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

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