JS利用XMLHttpRequest拦截ajax请求

function XMLHttpRequestBreak(fun=()=>false){
    let f = XMLHttpRequest.prototype.open;
	
	let add = function(){
		XMLHttpRequest.prototype.open = function(...args){
			check = fun(args);
			if(check){
				throw check;
			}
			f.apply(this,args)
		}	
	};
	
	let remove = function(){
		XMLHttpRequest.prototype.open = f	
	};
	
	return {add, remove}
}

test = XMLHttpRequestBreak();
test.add()
test.remove()

test = XMLHttpRequestBreak(()=>"123");
test.add()
test.remove()

test = XMLHttpRequestBreak(console.log);
test.add()
test.remove()

  

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