经过JS拦截 pushState 和 replaceState 事件

history.pushState 和 history.replaceState 能够在不刷新当前页面的状况下更改URL,可是这样就没法获取经过AJAX获得的新页面的内容了。
虽然各类HTML5文档说 window.onpopstate 事件能够拦截 pushState 的消息,但在实际的测试中, onpopstate 根本没有任何做用,没法拦截 pushState 的消息。app

通过Google一番,才找到了正确获取 pushState 事件的代码
https://stackoverflow.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 没法激活事件的问题了
另外记得最好将这段代码放在文档加载前执行测试

相关文章
相关标签/搜索