使用history.js,有没有一种方法可以确定状态的方向?

9

如标题所述,我希望能够在调用pushState函数时执行不同的onstatechange事件,而不是back函数。或者,如果go函数为正或负。

示例:

如果调用History.pushState()History.go(1),我希望statechange事件的回调是forwardPushState

如果调用History.back()History.go(-1),我希望statechange事件的回调是backwardsPushState


1
跟踪最后访问的页面,如果当前页面重定向到最后访问的页面,则很可能方向是向后的。 - adeneo
PushState将一个新状态推入堆栈中(状态是在执行新操作后存储的一些数据)。它与后退和前进没有关系。后退和前进是用于在堆栈中导航推送的状态的函数。我之所以这样说,是因为在您的编辑中,看起来您认为pushState和go(1)是等价的。 - Adib Aroui
@adeneo,请您能详细解释一下吗? - Adib Aroui
https://dev59.com/vFzUa4cB1Zd3GeqP0i6Y - user1987371
1
请关注这个话题,也许对您有用。那里有一个关于如何跟踪onstatechange事件的答案,以及如何知道用户何时单击了浏览器的前进/后退按钮。https://dev59.com/f3LYa4cB1Zd3GeqPXWlp - Adib Aroui
显示剩余2条评论
2个回答

7
一个状态是与页面相关的一些数据(如在浏览器中用户看到的)。如果用户想要进入某个页面,无论他是通过回退按钮还是前进按钮点击进入,该页面都是相同的。
PushState在堆栈中推入一个新状态。它与backgo没有关系。Backgo是用来在堆栈中导航的函数。我这样说是因为在你的编辑中,看起来你认为pushState和go(1)是等价的。
也许如果你想知道用户是从哪个方向来的,你应该分析onstatechange事件以了解它是否带有存储方向的参数,这不是一项简单的任务。
我认为主要的事情是它与go(-1)go(1)back没有关系。

我确实意识到pushStatego(1)并不相同,这只是一个例子。不幸的是,真的没有关系或链接可以做我正在寻找的事情,所以我必须像@adeneo所说的那样做一些事情。 - Ascherer

-1

或許這個對你有用。

<html>
<body onunload="disableBackButton()">
<h1>You should not come back to this page</h1>
</body>
<script>
function disableBackButton()
{
   window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
</html>

上述代码将使使用后退按钮加载此页面变得困难。

第二次尝试

下面的代码来自另一个堆栈溢出。

检测浏览器中的后退按钮点击

window.onload = function () {
if (typeof history.pushState === "function") {
    history.pushState("jibberish", null, null);
    window.onpopstate = function () {
        history.pushState('newjibberish', null, null);
        // Handle the back (or forward) buttons here
        // Will NOT handle refresh, use onbeforeunload for this.
    };
}
else {
    var ignoreHashChange = true;
    window.onhashchange = function () {
        if (!ignoreHashChange) {
            ignoreHashChange = true;
            window.location.hash = Math.random();
            // Detect and redirect change here
            // Works in older FF and IE9
            // * it does mess with your hash symbol (anchor?) pound sign
            // delimiter on the end of the URL
        }
        else {
            ignoreHashChange = false;   
        }
    };
}

}


不要试图禁用后退按钮。 - Ascherer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接