history.back()不适用于Chrome中预期的HTML5历史记录API

时间:2016-10-16 10:00:20

标签: javascript html5 google-chrome html5-history

history.back()函数应该让我回到使用HTML5历史记录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。我错过了什么吗?

1 个答案:

答案 0 :(得分:3)

在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

注意:只有Chrome 55支持带有once参数的addEventListener - 如果您希望侦听器运行一次,则必须在侦听器中调用removeEventListener,例如这样:

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