javascriptnode.jsgoogle-chrome-devtoolschrome-remote-debuggingtaiko

Get response of a API request made using chrome-remote-interface


I want to get the response data for the particular API call using chrome-remote-interface. I am not sure how to print the response. I am able to get the APIs that are being called using the demo code available in their GitHub repo.

Mentioned a screenshot that I need from Chrome DevTools.

  const chromeLauncher = require("chrome-launcher");
  const CDP = require("chrome-remote-interface");
  const axios = require("axios");

  (async function () {
    async function launchChrome() {
      return await chromeLauncher.launch({
        chromeFlags: ["--no-first-run", "--disable-gpu", "--no-sandbox"],
      });
    }

    const chrome = await launchChrome();
    const client = await CDP({
      port: chrome.port,
    });
    const { Network, Page } = client;
    await Page.enable();
    await Network.enable();
    await Page.navigate({ url: "[URL]" });
    await Page.loadEventFired();

    Network.requestWillBeSent((params) => {
      if (
        params.request.url ===
        "[URL]/rest/api/v1/ra/user?key=value&key=value"
      )
      {
        **Want to get the response for the API**
      }
    });
  })();

Solution

  • You can use Network.getResponseBody to fetch the body of the response you want. See this minimal example (I changed the target URL because the one you used wasn't immediately fetched, at least for me):

    const chromeLauncher = require('chrome-launcher');
    const CDP = require('chrome-remote-interface');
    
    (async function () {
        const chrome = await chromeLauncher.launch({
            chromeFlags: ['--no-first-run', '--disable-gpu', '--no-sandbox'],
        });
        const client = await CDP({
            port: chrome.port,
        });
    
        const {Network, Page} = client;
    
        Network.responseReceived(async ({requestId, response}) => {
            if (response.url === 'https://geolocation.onetrust.com/cookieconsentpub/v1/geo/location') {
                const {body, base64Encoded} = await Network.getResponseBody({requestId});
                console.log(body, base64Encoded);
            }
        });
    
        await Network.enable();
        await Page.navigate({url: '[URL]'});
    })();