当使用相同的location.href(或空)推送时,为什么window.onpopstate上的event.state为空 [英] Why is event.state on window.onpopstate empty when pushing with same location.href (or empty)

查看:156
本文介绍了当使用相同的location.href(或空)推送时,为什么window.onpopstate上的event.state为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不更改网址的情况下推送到历史记录和设置数据时:

When pushing to history and setting data without changing URL:

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

....然后听pop事件并按下后退按钮触发它浏览器:

.... 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
}

您将大部分时间获取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?

推荐答案

这是一个奇怪的问题,根据我的说法,它没有足够的记录。我在寻找这个问题的解决方案时遇到了麻烦。经过一个小时的沮丧谷歌搜索和尝试/提出不同的解决方案后,我注意到它开始工作时,我推动状态两次(或更多)。很明显event.state指的是被推的第二个最后一个状态。

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(..);

我希望这有助于某人!

这篇关于当使用相同的location.href(或空)推送时,为什么window.onpopstate上的event.state为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆