HTML5 历史 - 后退按钮到上一个完整页面?

HTML5 History - Back button to previous full page?

我正在使用 HTML5 历史记录 API 来修改 URL,因为选择了某些产品属性(例如绿色汽车、蓝色汽车)以允许深度-link分享.

但是,这不是单页应用,所以我不想劫持用户的后退按钮:如果他们按下后退键,我想让他们转到上一页,而不是前一辆车颜色.

实现此目标的最佳方法是什么?

历史示例:

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

然后按浏览器的后退按钮返回/page1

看来我应该一直在使用

history.replaceState();

而不是 history.pushState();。它取代了浏览器的 URL,但没有添加到历史对象中,因此后退按钮按我想要的方式工作。

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one.

developer.mozilla.org

这是一个使用 sessionStorage 的解决方案,它使您的应用程序能够转到以前存储的页面,而不会破坏可用性 expectations/browser 后退按钮功能。移动到上一个 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>

您可以看到,这允许用户更改查询字符串参数,但这不会影响您通过转发操作移动到上一页的功能,只需存储路径之间的更改即可。您可以使用一个数组来扩展它,而不是像我在这里所做的那样简单地使用两个值,但是如果您愿意的话,我会把它留给实施。