我正在使用新的HTML5 onpopstate事件。在Firefox 4中,当页面加载时会触发window.onpopstate事件,而在Webkit中似乎并不是这种情况。
哪种行为是正确的?
我正在使用新的HTML5 onpopstate事件。在Firefox 4中,当页面加载时会触发window.onpopstate事件,而在Webkit中似乎并不是这种情况。
哪种行为是正确的?
在某些情况下,当导航到会话历史记录条目时,将触发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
在页面加载时触发onpopstate是正确的做法,WebKit也很快会采用这种行为。WebKit 534.7 (Chrome 7.0.517.44)现在已经采用了这种方式。
我在Chrome上报告了一个错误,但事实证明这是期望的行为;这是处理某些后退/前进按钮操作所必需的。有关更多讨论和链接,请参见code.google.com上的此错误报告。
我仍在努力想出一个好的代码模式来处理onpopstate事件处理程序。
window.onload
上设置一个名为refreshed
的变量,并将其设置为false
,在history.pushState
调用时将其设置为true
。然后在 onpopstate
处理程序中,只有在refreshed
为false
时才进行操作。
看起来很傻,事实上也确实如此,但我无法做得更好。
window.onload
也会被触发,因此最好在其他地方初始化refreshed
。 - jamix我刚解决了这个问题,而修复方法实际上非常简单。Firefox在初始页面加载时不会触发onpopstate事件。当你触发一个popstate事件后,在page.load操作上返回false或阻止默认行为,就可以解决问题。
祝好运。
这里有一个实际例子: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.
}
AddEventHandler(window, 'popstate', OnPopState);
我需要做类似这样的事情:
AddLoadEvent(window.setTimeout(function()
{
AddEventHandler(window, 'popstate', OnPopState);
},0));
如果有人感兴趣,我已经想出了一个不错的模式来处理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.
}
};
});