2012-11-29 24 views
4

我第一次玩历史对象。我有我已经在铬测试下面的代码:html 5中的历史对象的event.state为空

<!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填充这个东西吗?

回答

6

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

(注:你可以通过任何可以被JSON.stringify版到pushState。)

你回到历史上的一个页面,但与pushState添加该页面,所以它没有“状态”。

点击“返回”后,尝试按下浏览器中的“转发”按钮。那么你会看到event.state不是null

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

+0

当你说“推动页面的当前状态”时,“当前状态”是否包含#box正在显示的状态= block?如果浏览器重新从历史记录中浏览,浏览器是否记得保留该框的可见性? – John

+0

@John:对不起,如果这是令人困惑。这就像正常浏览历史一样。浏览器只会将作为第一个参数传入的对象返回给'pushState'。它不会记住关于该页面的任何内容,除了URL。这取决于你。 –

+0

感谢你的回答。我跟进了另一个基本问题:http://stackoverflow.com/questions/13633691/html-5-history-remembers-restores-some-changes-and-not-others – John