javascript history onpopstate
I am trying to understand HTML5 history object. Here is a simple example which I started off with.
function addDialog(){
document.getElementById('d').style.display ='';
history.pushState({name:"changed"},"","#newURL");
}
window.onpopstate = function(e){
alert(e.state);
}
I have a div
with an id d
for which display
property is none
. On clicking a link, I will display the div and change the history so that new url will be loaded.
When I copy paste the开发者_如何转开发 new url, popstate
event is fired and I get null
for e.state
.
From what I understand, if I load the new url http://example.com#newURL
, e.state
should point to the object which I pushed using pushstate.
Please correct me if I am wrong and also I would like to know when e.state
gets populated.
As I tested, the e.state only get the pop state that you add to the history when you click in the Back or Forward button. Otherwise, it will give you the null.
You can use parameters to your URL so you can test if the request came from a history call or from an URL in the location bar.
onpopstate = function(event) {
alert('popEvent: ' + event);
if(event.state){
setupPage(event.state);
} else {
setupPage(getQStringParam('zid'));
}
}
精彩评论