HTML5历史记录-返回上一个完整页面按钮

HTML5 History - Back button to previous full page?

本文关键字:按钮 上一个 历史 记录 返回 HTML5      更新时间:2023-09-26

我正在使用HTML5历史API修改URL,因为选择了某些产品属性(例如绿色汽车、蓝色汽车),以允许深度链接共享。

然而,这不是一个单页应用程序,所以我不想劫持用户的后退按钮:如果他们按下后退按钮,我想允许他们转到上一页,而不是上一个汽车颜色。

实现这一目标的最佳方式是什么?

示例历史:

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

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

看起来我应该使用

history.replaceState();

而不是CCD_ 2。它替换了浏览器的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>

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