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

2022-01-11,,,,

下面小编就为大家带来一篇浅谈通过JS拦截 pushState和replaceState事件。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

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

经过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 无法激活事件的问题了

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

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

以上就是浅谈通过JS拦截 pushState和replaceState事件的详细内容,更多请关注本站其它相关文章!

《浅谈通过JS拦截 pushState和replaceState事件.doc》

下载本文的Word格式文档,以方便收藏与打印。