考虑以下几点:
var originalPath = window.location.pathname.toString();
history.pushState({ value: 'Foo' }, '', 'state-1');
history.pushState({ value: 'Bar' }, '', 'state-2');
history.pushState({ value: 'Baz' }, '', 'state-3');
history.back();
history.back();
console.log(history.state.value);
//So we can hit refresh and see the results again...
setTimeout(function() {
history.replaceState(null, '', originalPath);
}, 250);
人们期望这个代码块返回“富” - 在Firefox和我的IE鸭拳,这正是它 - 但是在Chrome中,它回应'巴兹'。
经过一番调查,我发现问题:IE和Firefox同步更新历史记录,然后在需要加载任何页面的情况下进行异步。 Chrome似乎立即发生异步。
证据:
window.onpopstate = function() {
console.log('ping');
}
history.pushState({ value: 'Foo' }, '', 'state-1');
history.back();
console.log('pong');
在Firefox中,这将返回 '平'; 'pong' - 表示该事件作为history.back()调用的一部分进行调度。在Chrome中,这返回'pong'; 'ping' - 表示该事件被放入队列中用于分派。
如果这个事件调度模型没有被用来管理历史和位置对象的状态 - 但显然是这样的,这并不会那么糟糕。
window.onpopstate = function() {
console.log('Event...', history.state, window.location.pathname.toString());
}
history.pushState({ value: 'Foo' }, '', 'state-1');
history.back();
console.log('Inline...', history.state, window.location.pathname.toString());
这是一个有趣的怪癖,需要使用jQuery延期链来解决我的单元测试问题。我对此并不特别高兴,但你能做什么?