【问题标题】:event.state of history object in html 5 is nullhtml 5 中历史对象的 event.state 为 null
【发布时间】:2012-11-17 23:15:26
【问题描述】:

我是第一次玩历史对象。我有以下代码,我一直在 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 填充它吗?

【问题讨论】:

    标签: javascript html history


    【解决方案1】:

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

    (注意:您可以将JSON.stringifyed 的任何内容传递给pushState。)

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

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

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

    【讨论】:

    • 当您说“推送页面的当前状态”时,“当前状态”是否包括 #box 为 display=block 的状态?如果从历史记录再次浏览,浏览器是否记得保留该框的可见性?
    • @John:很抱歉,如果这令人困惑。就像正常浏览历史一样。浏览器只会返回作为第一个参数传递给pushState 的对象。它不会记住有关页面的任何内容,除了 URL。这取决于你。
    • 感谢您的回答。我在这里跟进了另一个基本问题:stackoverflow.com/questions/13633691/…
    【解决方案2】:

    这是一个思考的想法。

    我在使用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)
    
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-21
      • 2013-10-07
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      相关资源
      最近更新 更多