Why is event.state on window.onpopstate empty when pushing with same location.href (or empty)

狂风中的少年 提交于 2019-12-23 07:26:51

问题


When pushing to history and setting data without changing URL:

window.history.pushState({
    stateName: "myStateName", 
    randomData: window.Math.random()
}, "myStateName", location.href);

.... and then listen to the pop event and trigger it by pressing the Back button in the browser:

window.onpopstate = function(event) {
  console.log(event.state); //logs null
}

You will most of the time get null as the state value instead of:

{
    stateName: "myStateName", 
    randomData: 0.34234234234
}

How can I solve this and why does this happen?


回答1:


This is a weird issue and according to me, it's not documented enough. I had loads of trouble with looking for a solution to this problem. After an hour of frustrated googling and trying/coming up with different solutions I noticed that it started working when I pushed the state twice (or more). It became clear that event.state referred to the second last state that was pushed.

So the answer to making this work is to push twice, listen once.

window.history.push(..);
window.history.push(..);

I hope this helps someone!



来源:https://stackoverflow.com/questions/28363645/why-is-event-state-on-window-onpopstate-empty-when-pushing-with-same-location-hr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!