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

ccr*_*san 6 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>
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*b W 2

在 Chrome中 ,history.back//不与. 我不久前在处理 PDF.js 时遇到了这个问题,并在 Chromium 的问题跟踪器上报告了该问题: https: //crbug.com/510026。但什么也没产生。history.forwardhistory.gohistory.state

解决方法是使用该popstate事件来检测导航何时完成:

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
Run Code Online (Sandbox Code Playgroud)

注意:addEventListenerwithonce参数仅在 Chrome 55 中受支持 - 在此之前,removeEventListener如果您希望侦听器运行一次,则必须调用侦听器,如下所示:

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