Alex29
Alex29

Reputation: 1251

Puppeteer: How to listen to a specific response?

I'm tinkering with the headless chrome node api called puppeteer.

I'm wondering how to listen to a specific request response and how to act in consequence.

I have look at events requestfinish and response but it gives me all the request/responses already performed in the page.

How can I achieve commented behaviour?

Upvotes: 41

Views: 65710

Answers (5)

ilyazub
ilyazub

Reputation: 1424

Since puppeteer v1.6.0 (I guess) you can use page.waitForResponse(urlOrPredicate[, options])

Example usage from docs:

const firstResponse = await page.waitForResponse('https://example.com/resource');
const finalResponse = await page.waitForResponse(response =>
  response.url() === 'https://example.com' && response.status() === 200
);
return finalResponse.ok();

Upvotes: 9

Schnitter
Schnitter

Reputation: 311

to get the xhr response simply do :

const firstResponse = await page.waitForResponse('https://example.com/resource')

// the NEXT line will extract the json response

console.log( await firstResponse.json() )

Upvotes: 0

storenth
storenth

Reputation: 1225

Filtered response (wait up to 11 seconds) body parsed as JSON with initially requested PATCH or POST method every time you will be call that:

const finalResponse = await page.waitForResponse(response => 
  response.url() === urlOfRequest 
  && (response.request().method() === 'PATCH' 
  || response.request().method() === 'POST'), 11);
let responseJson = await finalResponse.json();
console.log(responseJson);

Upvotes: 18

ckeeney
ckeeney

Reputation: 1386

I was using jest-puppeteer and trying to test for a specific response code of my test server. page.goto() resolves to the response of the original request.

Here is a simple test that a 404 response is returned when expected.

describe(`missing article page`, () => {
    let response;
    beforeAll(async () => {
        response = await page.goto('http://my-test-server/article/this-article-does-not-exist')
    })
    it('has an 404 response for missing articles', () => {
        expect(response.status()).toEqual(404)
    })

    it('has a footer', async () => {
        await expect(page).toMatch('My expected footer content')
    })
})

Upvotes: 2

Reniks
Reniks

Reputation: 551

One option is to do the following:

  page.on('response', response => {
    if (response.url().endsWith("your/match"))
      console.log("response code: ", response.status());
      // do something here
  });

This still catches all requests, but allows you to filter and act on the event emitter.

https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#event-response

Upvotes: 55

Related Questions