39

我在玩window.onpopstate,有件事让我有点恼火:

浏览器倾向于在页面加载时以不同的方式处理 popstate 事件。Chrome 和 Safari 总是在页面加载时发出 popstate 事件,但 Firefox 不会。

来源

我对其进行了测试,是的,在 Chrome 和 Safari 5.1+ 中,popstate 事件在页面加载时触发,但在 Firefox 或 IE10 中没有。

问题是,我只想收听popstate用户单击后退前进按钮(或通过 javascript 更改历史记录)的事件,但不想在页面加载时执行任何操作。

换句话说,我想将popstate事件与页面加载与其他popstate事件区分开来。

这是我到目前为止所尝试的(我正在使用 jQuery):

$(function() {
  console.log('document ready');

  setTimeout(function() {
    window.onpopstate = function(event) {
      // Do something here
    }, 10);
});

基本上我尝试将我的listener函数绑定到popstate足够晚,以便在页面加载时不绑定,只是稍后。

这似乎可行,但是,我不喜欢这种解决方案。我的意思是,我如何确定为 setTimeout 选择的超时时间足够大,但又不会太大(因为我不希望它等待太多)。

我希望有一个更聪明的解决方案!

4

4 回答 4

44

检查事件处理程序event.state中的布尔真值:popstate

window.addEventListener('popstate', function(event) {
    if (event.state) {
        alert('!');
    }
}, false);

To ensure this will work, always specify a non-null state argument when calling history.pushState() or history.replaceState(). Also, consider using a wrapper library like History.js that provides consistent behavior across browsers.

于 2013-04-09T08:40:37.880 回答
7

我遇到了类似的问题,我必须验证以确保页面是否已完全加载。

我用过这样的东西:

var page_loaded = false;    
window.onpopstate = function(event){
    if(!page_loaded){
       page_loaded = true;
       return false;
     }
    //Continue With Your Code
}
于 2013-04-09T08:27:28.183 回答
5

To react on popstate event, you need to push some state onto the session history.

For example add this line to the document ready section:

history.pushState(null, null, window.location.pathname);

Not ideal, but it works in Chrome, Firefox and other browsers as well.

Then the event is fired correctly when user clicks on Back or Forward button, also when history.back(), history.forward(), history.go() methods are called manually. Each time when popstate has been invoked, you have to push another state again to make it working.

See also:

于 2016-05-10T15:40:47.620 回答
2

It seems none of the browsers are emitting the event on page load any more as of today:

Browsers used to handle the popstate event differently on page load, but now they behave the same. Firefox never emitted a popstate event on page load. Chrome did until version 34, while Safari did until version 10.0.

Source: https://developer.mozilla.org/en-US/docs/Web/API/PopStateEvent

于 2019-09-18T21:32:20.793 回答