Utilizing headless Chrome to automatically capture AJAX requests

Chrome officially supports running the browser in headless mode, allowing for programmatic control through the Puppeteer API and/or the CRI library.

I've thoroughly explored the documentation but have not discovered a method to programmatically capture AJAX traffic from instances. I am looking to start a Chrome instance from code, navigate to a page, and access background response/request calls and raw data all within the code without using developer tools or extensions.

If you have any suggestions or examples on how this can be accomplished, I would greatly appreciate it. Thank you!

Answer №1

Update

In the comment, @Alejandro highlighted that the function resourceType returns a value in lowercase.

page.on('request', request => {
    if (request.resourceType() === 'xhr')
    // do something
});

Original answer

Puppeteer's API simplifies this process:

page.on('request', request => {
  if (request.resourceType === 'XHR')
    // do something
});

You can intercept requests using setRequestInterception, but it's unnecessary here unless you plan to modify the requests.

An example of intercepting image requests is available for reference.

The definitions of resourceTypes can be found here.

Answer №2

After much searching, I have finally discovered a way to achieve my goal. Utilizing chrome-remote-interface (CRI) and node.js, this can be accomplished with the following minimal code snippet.

const CDP = require('chrome-remote-interface');

(async function () {

    // Make sure you have an open Chrome instance with remote debugging enabled
    // For example, run: chrome --remote-debugging-port=9222
    const protocol = await CDP({port: 9222});

    const {Page, Network} = protocol;
    await Page.enable();
    await Network.enable(); // This is necessary in order to use Network.getResponseBody below

    Page.navigate({url: 'http://localhost/'}); // Replace 'http://localhost/' with your desired URL

    const onDataReceived = async (e) => {
        try {
            let response = await Network.getResponseBody({requestId: e.requestId})
            if (typeof response.body === 'string') {
                console.log(response.body);
            }
        } catch (ex) {
            console.log(ex.message)
        }
    }

    protocol.on('Network.dataReceived', onDataReceived)
})();

Answer №3

Using Puppeteer's listeners can assist in capturing xhr responses by utilizing the response and request events.

It is advisable to first verify if request.resourceType() is either xhr or fetch.

        listener = page.on('response', response => {
            const isXhr = ['xhr','fetch'].includes(response.request().resourceType())
            if (isXhr){
                console.log(response.url());
                response.text().then(console.log)
            }
        })

Answer №4

const browser = await puppeteer.launch();
const page = await browser.newPage();
const clientPage = page["_client"];
clientPage.on("Network.responseReceived", event => {
  if (~event.response.url.indexOf('/api/chart/rank')) {
    console.log(event.response.url);
    clientPage.send('Network.getResponseBody', {
      requestId: event.requestId
    }).then(async response => {
      const data = response.body;
      if (data) {
        try {
          const jsonData = JSON.parse(data);

        }
        catch (e) {
        }
      }
    });
  }
});

await page.setRequestInterception(true);
page.on("request", async request => {
  request.continue();
});
await page.goto('http://www.example.com', { timeout: 0 });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

show a fresh new page using react router

I have recently developed a mobile app that showcases a collection of movies. Currently, it is static and I am looking to implement a react router for navigation. Specifically, I want the user to be directed to a detail page for a TV Show when they click o ...

Is tsconfig.json Utilized by Gatsby When Using Typescript?

Many blog posts and the example on Gatsby JS's website demonstrate the use of a tsconfig.json file alongside the gatsby-plugin-typescript for TypeScript support in Gatsby. However, it seems like the tsconfig.json file is not actually utilized for conf ...

Storing information using ajax and JSON through Handsontable to send to a Web API

I am encountering an issue when sending my Handsontable data via ajax to a Web API POST method. The data appears as blank on the web api end despite showing up correctly in Fiddler. It seems like the data is not being deserialized. Below is my code snippet ...

What is the best way to integrate HybridAuth using an AJAX request?

I am currently working on setting up a single sign-on (SSO) login for a modx site and I have decided to use HybridAuth and Ajax for this purpose. However, I encountered an error that I am unsure how to resolve. Here is the code snippet: Below are a couple ...

Trouble with minified scripts on a particular server

Apologies if this has already been addressed, but I've been searching for a solution for hours. I created a basic website that works perfectly on my own hosting. However, when I transfer it to new hosting (same company, same package, different server ...

"Exploring the power of Ajax: a guide to automatically refreshing the response every

I am struggling to understand why this snippet of code isn't working as expected. The div updates when using .html, but not with my custom script. In my setup, I have two files: index.php and test.php The index file looks like this: $(document).rea ...

Angular can be used to compare two arrays and display the matching values in a table

Having two arrays of objects, I attempted to compare them and display the matching values in a table. While looping through both arrays and comparing them by Id, I was able to find three matches. However, when trying to display these values in a table, onl ...

React Form with Conditional Input Options and Validation

Just diving into the world of React, I find myself connecting a React frontend to a Flask backend in a group project. Surprisingly, I've ended up handling about 90% of the workload. While I have utilized MUI for implementing fields, my focus is more o ...

The V-model is failing to bind properly as anticipated

One feature of my application involves a table that displays a list of products. Each product row in the table has an input field where users can enter the quantity they want to purchase. The total cost for each product is dynamically calculated by multipl ...

How to call a function within a component from another component without encountering the "Cannot read property" error

Having trouble calling a function from one component in another by passing the reference of one to the other. I keep getting a "Cannot read property" error. Below is the code snippet Alert Component import { Component, OnInit, Output } from '@angula ...

Is there a way to incorporate a CSS file into this without explicitly mentioning the color?

I have successfully implemented a PHP solution for changing themes with a cookie that remembers the selected theme color when the user leaves the site. However, I now need to switch this functionality to JavaScript while still utilizing the CSS file. How c ...

Loading input datalist in Firefox postponed

My goal is to implement an input field for a username that allows users to select from a wide range of names/usernames. I want them to be able to enter a partial string from the name or username. Instead of loading the entire list initially, I aim to load ...

Getting the value from a .sh (Shell Script) file in React: How to do it?

There is a .sh file that contains the following code: echo "Hello" This code produces the output: Hello The question at hand is: I am trying to extract the output from the .sh file and integrate it into my React application. After exploring various ...

Retrieve the ID of the image element using Jquery from a collection of images within a div container

I'm encountering a simple issue that I can't seem to solve. I am working on a basic slider/gallery with the following functionalities: 1) "If button 1 is clicked, image one will appear." 2) "Clicking on button 2 will make IMAGE 1 slide left and I ...

Having trouble with opening and closing popup windows in JavaScript while using Android frames?

To display additional information for the user, I create a new tab using the following code: window.open("/Home/Agreement", "_blank"); Within the Agreement View, there is a button with JavaScript that allows the user to close the Popup and return to the m ...

Currently trapped within the confines of a Next.js 13 application directory, grappling with the implementation of a

I need to figure out how to export a variable from one component to layout.tsx in such a way that it is not exported as a function, which is currently causing the conditional check in the class name to always be true. Below is the code snippet: // File w ...

Troubleshooting: How to resolve the issue of receiving undefined values when passing API data to a child component with Axios in React

I am encountering difficulties in retrieving data that I pass to a child component. The issue may be related to the Promise not being resolved at the time of access, but I am unsure how to address it. My goal is to ensure that the data is fully retrieved f ...

The intricacies of the Jscript ReadLine() function

I am trying to figure out how to read the complete content of a .txt file using JavaScript. I know that ReadLine() can be used to read a specific line from a file, but I need a method that will allow me to read the entire contents of the file. I have searc ...

Send data through Ajax and Jquery to upload files

For hours on end, I've been grappling with how to use ajax to upload a file and coming up empty. Here's the snippet: HTML: <form action="" method="post" id="uploadForm" enctype="multipart/form-data"> <input type="file" name="image" ...

Error: The function window.intlTelInput is not recognized within the ReactJS framework

I am currently learning ReactJS and encountering an issue when using jQuery with React JS for intlTelInput. I have installed npm jQuery and imported all the necessary code. Additionally, I have included all the required CSS and jQuery links in my index.htm ...