4

我第一次玩历史对象。我有以下代码,我一直在 chrome 中测试:

<!DOCTYPE html>
<html>
        <head>
                <script type="text/javascript">

window.addEventListener('popstate', function(event) {
  console.log('popstate fired!');
   console.log(event.state);

});

function showbox()
{
   document.getElementById('box').style.display = 'block';
   history.pushState({somethinggoeshere:'but what?'}, 'I put text here, but how do i verify the browser has received it?', '?showbox=true');
}
                </script>
        </head>
        <body>
                <a onclick="showbox();">Show box</a>
                <div id="box" style="background:red; height:100px; display:none;"></div>
        </body>
</html>

当我单击链接显示框时,会出现一个红色框。当我单击 chrome 浏览器窗口中的后退按钮时,然后查看 console.log,event.state 为空。为什么它是空的?我不是用 history.pushState 填充这个吗?

4

2 回答 2

6

当您使用 时pushState,您将页面的“当前状态”(浏览器实际上并没有保存页面的状态。它只是将作为第一个参数传递的对象pushState与历史记录中的页面关联)到浏览器的历史记录堆。当您浏览到历史堆栈中的该页面时,您推送的对象将出现(在 中onpopstate)。

(注意:你可以传递任何可以JSON.stringify编辑的东西pushState。)

您回到历史中的一个页面,但该页面没有添加pushState,因此它没有“状态”。

单击“返回”后,尝试在浏览器中按下“前进”按钮。你会发现那event.state不是null

因此,您传递的对象链接到被推入历史堆栈的页面,并且您只有在访问历史记录中的该页面时才能看到它。

于 2012-11-29T19:36:32.143 回答
0

这是一个思考的想法。

我在使用Dart编程语言时遇到了同样的问题。PopStateEvent监听器null在事件状态参数中提供。我已经通过使用HashChangeEvent监听器解决了这个问题。在浏览器中按下“返回”按钮后,HashChangeEvent监听器被触发,提供有用的信息。

window.onHashChange.listen((event) {
    var e = event as HashChangeEvent;
    var newUrl = e.newUrl;
    var oldUrl = e.oldUrl;
      // please, navigate to the "state" (old history location)

  });
于 2020-06-05T18:47:39.743 回答