问题描述
我正在玩window.onpopstate
,有件事让我有些烦恼:
I'm playing with window.onpopstate
, and there is a thing that annoys me a little bit:
我测试了它,是的,在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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!