浅谈通过JS拦截 pushState和replaceState事件
history.pushState和history.replaceState可以在不刷新当前页面的情况下更改URL,但是这样就无法获取通过AJAX得到的新页面的内容了。
虽然各种HTML5文档说window.onpopstate事件可以拦截pushState的消息,但在实际的测试中,onpopstate根本没有任何作用,无法拦截pushState的消息。
经过Google一番,才找到了正确获取pushState事件的代码
https://stackoverflow.com/a/25673911
//Addthis: var_wr=function(type){ varorig=history[type]; returnfunction(){ varrv=orig.apply(this,arguments); vare=newEvent(type); e.arguments=arguments; window.dispatchEvent(e); returnrv; }; }; history.pushState=_wr('pushState'); history.replaceState=_wr('replaceState'); //Useitlikethis: window.addEventListener('pushState',function(e){ console.warn('THEYDIDITAGAIN!'); }); window.addEventListener('replaceState',function(e){ console.warn('THEYDIDITAGAIN!'); });
这段代码改写了history中原来的函数,然后自己激活一个事件
这样就可以解决pushState无法激活事件的问题了
另外记得最好将这段代码放在文档加载前执行
以上这篇浅谈通过JS拦截pushState和replaceState事件就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。