How do you intercept the server's response in XMLHtpRequest?
-
Is it possible to change XMLHtpRequest so that the contents of the response can be intercepted without replacing the entire object with all its methods?
It is expected that there will be challenges in the code like:x = new XMLHttpRequest(); x.open( "GET", "/" ); x.onreadystatechange = function () {...}; x.send( null );
or even one-point:
x = new XMLHttpRequest(); x.open( "GET", "/" ); x.send( null ); x.onreadystatechange = function () {...};
-
Decision for Blink
Blink is Chrome, Opera etc.
Prototype
XMLHttpRequest
onreadystatechange
as a ghetter/netter and assuring its ghetter/netter, the logic of work should not be broken.XMLHttpRequest
:var oldXMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
var xhr = new oldXMLHttpRequest();
// получаем дескриптор прототипных setter/getter
var descrGetSet = Object.getOwnPropertyDescriptor(
Object.getPrototypeOf( xhr ),
"onreadystatechange" );var newSet = function( val ) { console.log ( "setter" ); descrGetSet.set.call( xhr, function() { // прототипный setter console.log( "Inject "+this.status ); // this.responseText return val.apply( xhr, arguments ); } ); }
Object.defineProperty( xhr, "onreadystatechange", {
set: newSet, // новый setter
get: descrGetSet.get // старый getter
} );return xhr;
}
Now make:
x = new XMLHttpRequest();
x.open( "GET", "/" );
x.send( null )
x.onreadystatechange = function () { console.log( this.statusText+' is 2' )};
See.
Inject 200
OK is 2
Inject 200
OK is 2
Inject 200
OK is 2
Which should be when you change.
readyState
♪Decision for Webkit
Webkit - Safari, PhantomJS
The problem is this move--
onreadystatechange
It's a ghetter.XHR
NotXHR.prototype
♪ You can't redesign it. Learn fromXHR
You can't, too, so you need to use a vest.XHR
♪
It's very good.
https://github.com/ilinsky/xmlhttprequest