获取使用 chrome-remote-interface 发出的 API 请求的响应

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

提问人:Priyom saha 提问时间:1/31/2022 最后编辑:Priyom saha 更新时间:9/13/2022 访问量:1175

问:

我想使用 chrome-remote-interface 获取特定 API 调用的响应数据。 我不确定如何打印回复。我能够使用其 GitHub 存储库中提供的演示代码获取正在调用的 API。

提到了我需要从 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**
      }
    });
  })();
javascript 节点:.js google-chrome-devtools chrome-remote-debugging taiko

评论


答:

4赞 cYrus 1/31/2022 #1

您可以使用 Network.getResponseBody 获取所需响应的正文。请参阅此最小示例(我更改了目标 URL,因为您使用的 URL 没有立即获取,至少对我来说是这样):

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]'});
})();