浅谈通过JS拦截 pushState和replaceState事件

history.pushState 和 history.replaceState 可以在不刷新当前页面的情况下更改URL,但是这样就无法获取通过AJAX得到的新页面的内容了。

虽然各种HTML5文档说 window.onpopstate 事件可以拦截 pushState 的消息,但在实际的测试中, onpopstate 根本没有任何作用,无法拦截 pushState 的消息。

经过Google一番,才找到了正确获取 pushState 事件的代码

https://*.com/a/25673911

// Add this:
var _wr = function(type) {
  var orig = history[type];
  return function() {
    var rv = orig.apply(this, arguments);
    var e = new Event(type);
    e.arguments = arguments;
    window.dispatchEvent(e);
    return rv;
  };
};
history.pushState = _wr('pushState');
history.replaceState = _wr('replaceState');

// Use it like this:
window.addEventListener('pushState', function(e) {
  console.warn('THEY DID IT AGAIN!');
});
window.addEventListener('replaceState', function(e) {
  console.warn('THEY DID IT AGAIN!');
});

这段代码改写了 history 中原来的函数,然后自己激活一个事件

这样就可以解决 pushState 无法激活事件的问题了

另外记得最好将这段代码放在文档加载前执行

以上这篇浅谈通过JS拦截 pushState和replaceState事件就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。