2

I have the following Typescript function that assumes a Chrome browser has already been launched using Puppeteer. The documentation for the Fetch functions used below can be found here.

async function modify(client: CDPSession) {
    client.on('Fetch.requestPaused', async ({ requestId, request, frameId, resourceType, responseErrorReason, responseStatusCode, responseHeaders, networkId }) => {
        // Correctly prints out the User-Agent header's value
        console.log(request.headers["User-Agent"]);

        // After this line is run, I can inspect the request.headers object and see that User-Agent was successfully edited
        request.headers['User-Agent'] = 'trying to edit this header';

        // Continuing the request gives an error
        await client.send('Fetch.continueRequest', {
            requestId: requestId,
            headers: request.headers,
        });
    });
}

Here is the specific error I'm seeing:

Error: Protocol error (Fetch.continueRequest): Invalid parameters headers: array expected

How can I resolve this error and successfully modify the request.headers? Is this a silly Javascript/Typescript syntax issue that I just can't figure out?

hardkoded
  • 18,915
  • 3
  • 52
  • 64
aBlaze
  • 2,436
  • 2
  • 31
  • 63
  • `headers` in the `send` function is array, so you need to set it `[{name: 'User-Agent', value: 'trying to edit this header'}]` – Sora Shiro Aug 21 '19 at 18:06

1 Answers1

3

Fetch.requestPaused returns the headers as an object. e.g.:

{
    "Upgrade-Insecure-Requests":"1",
    "Accept": "text/html,application/xhtml+xml"}
}

Fetch.continueRequest expects an Array<{name: string, value: string}>. e.g.

[
    {"name": "Accept", value: "text/html,application/xhtml+xml"}
]

You can use the code that Puppeteer is using:

function headersArray(headers) {
  const result = [];
  for (const name in headers) {
    if (!Object.is(headers[name], undefined))
      result.push({name, value: headers[name] + ''});
  }
  return result;
}
hardkoded
  • 18,915
  • 3
  • 52
  • 64
  • Unfortunately with the `headersArray` function, I'm still getting this error message: Error: Protocol error (Fetch.continueRequest): Invalid parameters headers: array expected – aBlaze Aug 21 '19 at 20:11
  • 1
    On second try, it is working. I must not have done a Visual Studio rebuild on the Typescript project. Thanks! Marking your answer as accepted. – aBlaze Aug 21 '19 at 20:55