Blogging without javascript

Simple trick to intercept puppeteer's browser response

Intercept the browser response

If you are using Puppeteer for a while and wanted to intercept the responses, your problems are over!

Here is a quick solution to have the response of a request to be written into the CLI.

Let's start with a simple setup:

const browser = await launchTheBrowser()
const page = await getSomeBrowserPage(browser)

Create your launchTheBrowser(), getSomeBrowserPage(browser) functions whatever way you'd like.

This is how to intercept a browser's request using puppeteer:

page.setRequestInterception(true)

page.on('request', (request) => {
    request.continue()
})

page.on('requestfinished', async (request) => {
    const response = request.response()
    const buffer = await response.buffer()
})

After await page.setRequestInterception(true) all request in the browser will be automatically hindered for you to handle.

According to the documentation after the above function is invoked the methods request.abort, request.continue and request.respond are enabled. This provides the capability to modify network requests that are made by a page.

Now you must start listening to the request and requestfinished page events.

The first event that will be triggered is request. Here you should just use the, now available, request.continue method.

Now the event requestfinished is being triggered and you have the response you can just read the buffer using the, newly available, method request.buffer, and it's done!

The buffer object represents a standard Nodejs Buffer object.

dptoledo@pm.me

#browser #intercept #puppeteer #request #response