Intercept XMLHttpRequest in Worker Runtime


As it stands, it seems that the following listener available in workers:

addEventListener('fetch', event => {})

only intercepts events dispatch by the native browser fetch methods. This presents an issue when it is necessary to intercept, and work with XMLHttpRequest s. I have had some luck using the ElementHandler to insert scripts in the head of pages, to modify the XMLHttpRequest prototype.



    class ElementHandler {
        element(element) {
            element.prepend(' <
                script >
                XMLHttpRequest.prototype.realOpen =;
                var myOpen = function(method, url) {
                    // make modifications
                    this.realOpen(method, finalUrl);
                //ensure all XMLHttpRequests use our custom open method
       = myOpen; <
                ', { html: Boolean })

But this is very messy! Is there any way to intercept XMLHttpRequest in the worker runtime?

I am not quite sure about your question.

What do you want to “intercept”? Workers do not support “XMLHttpRequest” so there is nothing to “intercept” in the first place. Now, if you mean requests sent via it from the browser, then these will be regular HTTP requests on Cloudflare’s side just like everything else.

1 Like

Thank you for your response, and let me try to clarify.

Imagine I do this in the browser:

  .then((response) => {
    return response.json();

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);"GET", "");

Image I have this in a worker

addEventListener('fetch', event => {console.log(event)})

In my experimentation, it seems like the fetch event listener in the worker will fire in response to the fetch request made in the browser, but not the response to the XMLHttpRequest made in the browser. Is this actually the case?

These are completely independent. The Worker code has no relation whatsoever to anything running in the browser. It simply handles incoming requests, regardless of how you sent them.

1 Like