JS给XMLHttpRequest添加filter

function XMLHttpRequestFilter(){
    let base = XMLHttpRequest.prototype.open;
	
	let filter_list = [];
	
	let add = function(fun, key='_fn'){
		filter_list.push([key, fun])
		XMLHttpRequest.prototype.open = function(...args){
			filter_list.map(x=>{
				let check = x[1](args)
				if(check){
					throw check; 
				}
			});
			base.apply(this,args)
		}	
	};
	
	let remove = function(key='_fn'){
		filter_list = filter_list.filter(x=>x[0]!=key);
	};
	
	let removeAll = function(){
		filter_list.length=0;
		XMLHttpRequest.prototype.open = base	
	};
	
	return {add, remove, removeAll}
}

t.add(console.log, 'k1')
t.add(console.dir, 'k2')
t.add(console.log, 'k3')

t.remove('k2')
t.removeAll()

t.add(console.log, "k1")
t.add(()=>"123", 'k2')
t.add(console.dir, "k1")

t.remove("k2")

  

posted @ 2019-07-18 20:37  413Xiaol  阅读(378)  评论(0编辑  收藏  举报