gpt4 book ai didi

javascript - history.back() 不能像 Chrome 中预期的那样与 HTML5 history API 一起使用

转载 作者:太空狗 更新时间:2023-10-29 15:10:33 25 4
gpt4 key购买 nike

history.back() 函数应该让我在使用 HTML5 history API 创建的历史中返回一步。以下代码在 Firefox 中按预期工作,但在 Chrome 中不工作:

<html>
<script type="text/javascript">
history.replaceState({path: '/home'}, '', '?page=home');
history.pushState({path: '/second'}, '', '?page=second');
console.log(history.state.path); // says "/second"
history.back();
console.log(history.state.path); // says "/second" but should say "/home"
</script>
</html>

在 Chrome 中,它会打印 /second 两次,而返回后它应该打印 /home。我错过了什么吗?

最佳答案

在 Chrome 中,history.back/history.forward/history.gohistory.state 不同步。我 encountered this issue a while back while working on PDF.js ,并在 Chromium 的问题跟踪器上报告:https://crbug.com/510026 .但是没有任何结果。

解决方法是使用 popstate event检测导航何时完成:

history.replaceState({path: '/home'}, '', '?page=home');
history.pushState({path: '/second'}, '', '?page=second');
console.log(history.state.path); // says "/second"

addEventListener('popstate', function(event) {
console.log(history.state.path); // says "/home"
// You can also use console.log(event.state);
}, {once: true});
history.back(); // Will asynchronously change history.state

备注:addEventListener仅从 Chrome 55 开始支持使用 once 参数 - 在此之前,如果您希望监听器运行一次,则必须在监听器中调用 removeEventListener,如下所示:

addEventListener('popstate', function listener(event) {
removeEventListener('popstate', listener);
console.log(history.state.path); // says "/home"
// You can also use console.log(event.state);
});

关于javascript - history.back() 不能像 Chrome 中预期的那样与 HTML5 history API 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40069052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com