Monkeypatch Javascript constructor

618 Views Asked by At

I've read all of the other related answers I've been able to find, but none has worked. Essentially, I want to make this source: https://github.com/gildas-lormeau/zip.js/blob/master/WebContent/zip-ext.js

add some custom headers to the XMLHttpRequest on line 93. Since HTTPRangeReader is wrapped in an anonymous function, I can't monkeypatch it directly, and it seems the only option is to monkeypatch the XMLHttpRequest constructor. I just need to call the default constructor and then call setRequestHeader() one or more times before returning the new object.

1

There are 1 best solutions below

0
On

Use an alias to clone the original then reference it in the method override:

    function handler()
      {
      console.log(JSON.stringify(arguments));
      }

    /* Avoid stack overflow */
    if (XMLHttpRequest.prototype.mySetRequestHeader === undefined)
      { 
      XMLHttpRequest.prototype.mySetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
      }

    /* Override prototype method */
    XMLHttpRequest.prototype.setRequestHeader = function baz(foo, bar)
      {
      XMLHttpRequest.prototype.mySetRequestHeader.call(this, 'foo', 'bar');
      XMLHttpRequest.prototype.mySetRequestHeader.call(this, 'bar', 'baz');
      
      }

    /* Test the override */
    with (new XMLHttpRequest)
      {
      open('GET', location.href);
      setRequestHeader("referer","http://www.example.com");
      send("");
      onreadystatechange = handler;
      }

References