点击后退按钮后,Chrome 35会触发popstate

时间:2014-07-06 09:40:03

标签: javascript jquery google-chrome popstate

我知道有许多与chrome和popstate事件相关的主题,但在将chrome升级到35版之后我遇到了一个新主题。

情况就是这样:

在您选择类别,页面等之后,我有一个包含类别和过滤器的列表页面。内容通过ajax重新加载,所有内容都由历史API处理,效果很好。

但是当你去列表中的项目的详细页面 - 标准请求,整个页面被重新加载 - 然后按下浏览器上的后退按钮,你可以看到一个列表页面在你最后点击一个项目的位置,然后触发popstate(我不会在这里谈论初始页面加载时的chrome popstate因为版本34 popstate不再在init上触发,并且由于我之前提到的处理类别的代码重新加载整个页面。

所以问题是我们按回按钮后chrome 35会触发popstate事件,我的问题是:

如何检测用户从详细信息页面返回到我的列表页面后再触发此事件时触发此事件。

我尝试使用文档对象引用等。但是当它第一次看起来像是解决方案的时候总会出现它无法工作的情况。

1 个答案:

答案 0 :(得分:0)

我一直在遇到这个问题。我的解决方案有点像黑客,但它看起来效果不错。我发现在设置我的onpopstate处理程序之前等待150ms足以等待Chrome运行其最初的onpopstate处理程序,你可以使用它来获得“优势”。例如,要检测是否运行了初始onpopstate:

// wait for page to load
$(function() {
  var no_initial_onpopstate = true;
  var enabled = true;

  window.onpopstate = function() {
    if(!enabled) return;
    console.log("detected initial onpopstate");
    no_initial_onpopstate = false;
  }

  setTimeout(function() {
    enabled = false;
    console.log("No initial onpopstate: ", no_initial_onpopstate);

    // no_initial_onpopstate indicates if the browser emitted an initial
    // onpopstate event. Do with that information what you will

    // 150ms delay seems to be the "magic number" to wait for Chrome to
    // run all of its initial onpopstate handlers (in my tests on localhost, at least)
  }, 150);
});

因此,我认为在浏览器的DOM就绪事件150ms之后设置你的`onpopstate'回调将跳过chrome的初始onpopstate。