JS intercept ajax request using XMLHttpRequest

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()

  

Guess you like

Origin www.cnblogs.com/413xiaol/p/11209819.html