0

I'm writing a plugin that will intercept all the requests and responses and will extract data and if needed also modify the response. Below is the code I'm using to intercept the request, but it seems I can only read the response and not modify it. The code is injected into the page by manifest.json.

(function(xhr) 
{
    var XHR = XMLHttpRequest.prototype;
    var send = XHR.send;

    XHR.send = function(postData) 
    {
        this.addEventListener('load', function()
        {
            if (postData) 
            {
                if (typeof postData === 'string') 
                {
                    try 
                    {
                        this._requestHeaders = postData;
                    } catch (err) 
                    {
                        console.log(err);
                    }
                } 
                else if (typeof postData === 'object' || typeof postData === 'array' || typeof postData === 'number' || typeof postData === 'boolean') 
                {
                    var enc = new TextDecoder("utf-8");
                    requestdata = enc.decode(postData);
                    console.log("postData");
                    var json = JSON.parse(requestdata);
                    console.log(json);
                    // Extract data from request

                    var req = this.responseText
                    // Change req, this does nothing!
                    this.responseText = req;
                }
            }            
        });
        return send.apply(this, arguments);
    };
})(XMLHttpRequest);

I understand this is because responseText is actually read only, and then property itself returns a cloned string, rather than a reference to actual response text. Is there any way around it? The only other way I see is using CEF, opening a web site from my CEF application and intercepting the requests there, which is nice, I can enhance the web site inside my application, but on the other hand it's cumbersome and I want my users to be able to download the plugin instead of having to use an exe.

Thanks!

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
user1617735
  • 451
  • 5
  • 16
  • Try `Object.defineProperty(this, 'responseText', {value: req})` – wOxxOm Jul 30 '22 at 05:21
  • @wOxxOm Hi, this indeed works, but the original request still recieves the unmodified response. I can't see the source code, so I can only guess how they do it. Is there any other way to read the response except for via responseText properly? Like using onLoad event or onReadyStateChange? Is there any way to intercept those as well? Thanks! – user1617735 Jul 30 '22 at 23:27
  • Object.defineProperty(XHR, 'responseText', {get: () => req}) – wOxxOm Jul 31 '22 at 04:07

0 Answers0