history.go()方法之后,history.replaceState()为什么不起作用?

问题描述 投票:0回答:1

这是一个示例javascript代码

function history() {
   window.history.pushState('','','#page1');
   window.history.pushState('','','#page2');
   window.history.pushState('','','#page3');
   window.history.go(-1);
   window.history.replaceState('','','#replaced');
}
// expected result in url is www.somewhere.com/#replaced
// but result is /#page2

实际上,我想浏览第一页并替换一下history.state

有解决这个问题的主意吗?

javascript web-applications browser-history
1个回答
0
投票

这是因为history.go()方法是异步的。 MDN上的文档说:

此方法是异步的。为popstate方法添加一个侦听器,以确定导航何时完成。

因此执行了history.go()之前 replaceState完成了。这就是导致此问题的原因。

go(-1)事件与History API结合使用可返回并替换正确的状态。每当您返回到历史记录集合的状态时,都会触发popstate事件。使用popstatehistory.go(-1)或在浏览器中按返回按钮都将触发它。

并且如果您要返回到first页面,则将history.back()值设置为.go(),因为您想返回历史记录中的两个位置。

在事件侦听器中,检查您当前所在位置的-2值。这将让您知道是否到达正确的页面。然后使用location.hash正确设置状态。

replaceState
© www.soinside.com 2019 - 2024. All rights reserved.