Created
January 13, 2020 08:53
-
-
Save xiopt/1d63bfa93311a64f255f3dc51b414971 to your computer and use it in GitHub Desktop.
Intercept XHR requests so that we can do something useful with it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Taken from https://stackoverflow.com/a/27363569 | |
// Allows for the object to be interrogated | |
((() => { | |
const origOpen = XMLHttpRequest.prototype.open; | |
XMLHttpRequest.prototype.open = function() { | |
console.log('request started!'); | |
this.addEventListener('load', function() { | |
console.log('request completed!'); | |
console.log(this.readyState); //will always be 4 (ajax is completed successfully) | |
console.log(this.responseText); //whatever the response was | |
}); | |
origOpen.apply(this, arguments); | |
}; | |
}))(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Taken from https://stackoverflow.com/a/5202999 | |
// This is only good for logging. | |
function addXMLRequestCallback(callback){ | |
let oldSend; | |
let i; | |
if( XMLHttpRequest.callbacks ) { | |
// we've already overridden send() so just add the callback | |
XMLHttpRequest.callbacks.push( callback ); | |
} else { | |
// create a callback queue | |
XMLHttpRequest.callbacks = [callback]; | |
// store the native send() | |
oldSend = XMLHttpRequest.prototype.send; | |
// override the native send() | |
XMLHttpRequest.prototype.send = function(){ | |
// process the callback queue | |
// the xhr instance is passed into each callback but seems pretty useless | |
// you can't tell what its destination is or call abort() without an error | |
// so only really good for logging that a request has happened | |
// I could be wrong, I hope so... | |
// EDIT: I suppose you could override the onreadystatechange handler though | |
for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) { | |
XMLHttpRequest.callbacks[i]( this ); | |
} | |
// call the native send() | |
oldSend.apply(this, arguments); | |
} | |
} | |
} | |
// e.g. | |
addXMLRequestCallback( xhr => { | |
console.log( xhr.responseText ); // (an empty string) | |
}); | |
addXMLRequestCallback( xhr => { | |
console.dir( xhr ); // have a look if there is anything useful here | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment