How would go about monkey patching the XMLHTTPRequest‘s onreadystatechange function. I’m trying to add a function that would be called when every ajax request made from a page come back.
I know this sounds like a terrible idea, but the use case is quite peculiar. I want to use a certain SDK with a console (jqconsole) but show status and results from ajax calls within the console without modifying the external SDK.
I’ve looked at this post which had great info, but nothing on monkey patching the callback which seem to exceed my JavaScript skills.
P.S Can’t use jQuery since it only supports ajax calls made from jQuery not from XMLHTTPRequests directly which is the case here.
To monkey-patch
XMLHttpRequests, you need to know how an AJAX request is generally constructed:setRequestHeader(),open()).send).General-purpose patch
The previous assumed that
onreadystatechangewas assigned to theonreadystatechangehandler. For simplicity, I didn’t include the code for other events, such asonload. Also, I did not account for events added usingaddEventListener.The previous patch runs for all requests. But what if you want to limit the patch to a specific request only? A request with a certain URL or async flag and a specific request body?
Conditional monkey-patch
Example: Intercepting all
POSTrequests whose request body contains “TEST”The main techniques used is the transparent rewrite using…
My examples are very basic, and can be extended to meet your exact wishes. That’s up to you, however.