Search code examples
javascriptnode.jstypescriptpuppeteerchrome-devtools-protocol

How to modify request headers using Puppeteer & Chrome DevTools Protocol? (Possibly a JS syntax issue)


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?


Solution

  • 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;
    }