You can intercept network requests in Puppeteer using the page.setRequestInterception
method. Here's an example of how you can intercept network requests and log the request URL and method:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', request => {
console.log('Request URL:', request.url());
console.log('Request Method:', request.method());
request.continue();
});
await page.goto('https://example.com');
await browser.close();
})();
In this example, we use the page.setRequestInterception(true)
method to enable request interception. We then add a event listener for the 'request' event, which is triggered whenever a new network request is made. Inside the event listener, we log the request URL and method using request.url()
and request.method()
, respectively.
You can also modify the request or respond to it in different ways within the event listener. For example, you can abort the request, modify its headers, or even mock the response. Check out Puppeteer's documentation for more information on how to manipulate network requests.