页面加载时HTML5 onpopstate

时间:2010-09-13 12:40:50

标签: javascript html5

我正在使用新的HTML5 onpopstate事件。使用Firefox 4,window.onpopstate事件在页面加载时触发,而在Webkit中似乎并非如此。

哪种行为正确?

6 个答案:

答案 0 :(得分:10)

  

导航到会话历史记录条目时,在某些情况下会触发popstate事件。

http://www.whatwg.org/specs/web-apps/current-work/#event-popstate

从我的理解,虽然我可能是错的,看到加载页面确实意味着历史记录被创建并遍历到,是的,它应该在页面加载时触发。

另见,

http://www.mail-archive.com/whatwg@lists.whatwg.org/msg19722.html

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

答案 1 :(得分:4)

在页面加载时启动onpopstate是正确的,WebKit很快就会出现这种情况。 WebKit 534.7(Chrome 7.0517.44)现在就是这样的。

我在其上提交了一个Chrome错误,但事实证明这是理想的行为;需要它才能正确处理某些后退/前进按钮操作。有关更多讨论和链接,请参阅this bug report at code.google.com

我仍在尝试为onpopstate事件处理程序提供一个好的代码模式。

答案 2 :(得分:3)

我不知道这是不是你问的问题,但我对 ajax-only onpopstate事件处理程序的解决方案是设置true变量{{1} } refreshed上的window.onload并在false来电时设置为history.pushState;然后在onpopstate处理程序上,如果refreshedfalse,则执行操作。

看起来很傻,但确实如此,但我无法做得更好。

答案 3 :(得分:3)

刚刚解决了这个问题,修复实际上非常简单。 Firefox在初始页面加载时不会触发onpopstate。解雇一个popstate后,返回false或阻止page.load操作的默认值,你就是黄金。

干杯。

在此采取行动:www.thecoffeeshopnyc.com

// Write in a new handler for Firefox, which does not fire popstate on load.
// Modern Webkit browsers fire popstate on load. The event handler below fires the controller
$(window).load(function () {
    if ($.browser.mozilla) {
        // Your func.
    }
})

// Add the event listener. If the above is false, it will still run as intended in normal browsers.
window.onpopstate = function() {
    // Your func.
}

答案 4 :(得分:1)

  

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

此引用来自Mozilla的文档:https://developer.mozilla.org/en-US/docs/DOM/window.onpopstate

我倾向于同意Mozilla系统。页面加载不是需要触发额外popstate事件的操作,因为状态未被弹出,它是第一次加载。

我猜测Webkit是为了方便而做的...在我的所有实现中,在初始popstate被触发之前,延迟加载我的处理程序一直是一个不便。

而不是这个(使用伪函数):

AddEventHandler(window, 'popstate', OnPopState);

我必须做这样的事情:

AddLoadEvent(window.setTimeout(function() 
    { 
        AddEventHandler(window, 'popstate', OnPopState); 
    },0));

答案 5 :(得分:1)

如果有人感兴趣,我会想出一个合适的模式来处理onpopstate(这段代码假设jQuery,为了清晰起见而剥离了特征检测检查):

$(function() {

  // 1. Add initial state to current history record on page load.
  var href = location.href;
  history.replaceState({"href": href}, null, href);

  // 2. Now attach the popstate handler.
  window.onpopstate = function(ev) {

    // Raised on page load this event will still contain no state.
    var state = ev.state;
    if (state && state.href) {

      // 3. Add your logic, use `state` and `state.href` as you see fit.          

    }
  };

});