import * as Tools from "../tool"; class TracerEvent { //拦截window.history.pusgState原生方法 private _pushState: any; private _replaceState: any; //时间监听处理方法集 private handlePageChangeEventList: any[]; private isPageChangeHandle : boolean; constructor() { this.handlePageChangeEventList = []; this.isPageChangeHandle = false; this.resgisterPageChangeEventListener(); } private resgisterPageChangeEventListener = () => { //监听相关内容 var self = this; //hashchange (window).addEventListener("hashchange",this.onHandleEvent); //pushStateModel replaceStateModel self._pushState = window.history.pushState; window.history.pushState = function(state, title, url) { let oldURL = window.location.href; let newURL = url ? url : oldURL; // hook self.onHandleEvent({ eventName:'pushState', oldURL, newURL, state, title, }) //run return self._pushState.apply(window.history, arguments); }; self._replaceState = window.history.replaceState window.history.replaceState = function(state, title, url) { let oldURL = window.location.href; let newURL = url ? url : oldURL;// hook self.onHandleEvent({ eventName:'replaceState', oldURL, newURL, state, title, }) return self._replaceState.apply(window.history, arguments); }; }; private checkPageUrlChange = (oldUrl,newUrL) => { //其中某一次不存在 if(!oldUrl || !newUrL || !Tools.isString(oldUrl) || !Tools.isString(newUrL) ){ return false; } //has path没有变化 if(newUrL.indexOf('?') > -1 && oldUrl.indexOf('?') > -1){ let newPath = newUrL.split('?')[0] let oldPath = newUrL.split('?')[0] if( newPath === oldPath){ return false; } } return true } private onHandleEvent = (event) => { if(this.isPageChangeHandle){ return false; } const{ newURL , oldURL } = event if(!this.checkPageUrlChange(oldURL,newURL)){return false} //on Hook this.isPageChangeHandle = true Tools.asynGenerator( (next) => { this.handlePageChangeEventList.forEach( (onHook) =>{ try{ onHook(event) }catch(e){ console.error(e) } }) next() }, (next) =>{ this.isPageChangeHandle = false } ) } //注册页面跳转事件处理钩子 public addPageChangeEventLister = (onHandleHook) => { if(Tools.isFunction(onHandleHook)){ this.handlePageChangeEventList.push(onHandleHook) } } public stopPageChangeEventCatch = () => { window.history.pushState = this._pushState window.history.replaceState = this._replaceState this._pushState = false this._replaceState = false; (window).removeEventListener("hashchange",this.onHandleEvent); } public resumePageChangeEventCatch = () => { this.resgisterPageChangeEventListener() } } export default TracerEvent;