如何忽略页面加载时的window.onpopstate? [英] How can I ignore window.onpopstate on page load?

查看:407
本文介绍了如何忽略页面加载时的window.onpopstate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩window.onpopstate,有件事让我有些烦恼:

I'm playing with window.onpopstate, and there is a thing that annoys me a little bit:

浏览器在页面加载时倾向于不同地处理popstate事件. Chrome和Safari总是在页面加载时发出popstate事件,但是 Firefox没有.

Browsers tend to handle the popstate event differently on page load. Chrome and Safari always emit a popstate event on page load, but Firefox doesn't.

我测试了它,是的,在Chrome和Safari 5.1+中,popstate事件是在页面加载时触发的,但在Firefox或IE10中不会触发.

I tested it, and yeah, in Chrome and Safari 5.1+ the popstate event is fired on page load, but not in Firefox or IE10.

问题是,我只想听用户单击 back forward 按钮(或通过javascript更改了历史记录)的popstate事件,但不想在页面加载上做任何事情.

The problem is, that I want to listen only to popstate events where user clicked the back or forward button (or the history was changed via javascript), but don't want to do anything on pageload.

换句话说,我想区分popstate事件和页面加载与其他popstate事件.

By other words I want to differentiate the popstate event from page load from the other popstate events.

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

This is what I tried so far (I'm using jQuery):

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

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

基本上,我尝试将我的listener函数绑定到popstate的时间足够晚,以至于不会在页面加载时绑定,直到以后.

Basically I try to bind my listener function to popstate late enough to be not bound on page load, only later.

这似乎可行,但是,我不喜欢这种解决方案.我的意思是,如何确定为setTimeout选择的 timeout 足够大,但又不要太大(因为我不想让它等待太多).

This seems to work, however, I don't like this solution. I mean, how can I be sure that the timeout chosen for setTimeout is big enough, but not too big (because I don't want it to wait too much).

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

I hope there is a smarter solution!

推荐答案

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

Check for boolean truth of event.state in popstate event handler:

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

为确保此功能有效,请在调用history.pushState()history.replaceState()始终指定非null状态自变量.另外,考虑使用类似 History.js 的包装库,该包装库可在浏览器之间提供一致的行为.

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.

这篇关于如何忽略页面加载时的window.onpopstate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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