41

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?

marli
  • 529
  • 10
  • 19
Alex29
  • 1,211
  • 2
  • 10
  • 20
  • 1
    Have you seen https://github.com/GoogleChrome/puppeteer/blob/master/examples/block-images.js#L24-L29? That shows how to intercept network requests, examine them, and either continue/abort the request. – ebidel Aug 22 '17 at 21:10

5 Answers5

53

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

Reniks
  • 531
  • 4
  • 3
16

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);
storenth
  • 967
  • 11
  • 18
7

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();
ggorlen
  • 44,755
  • 7
  • 76
  • 106
ilyazub
  • 1,226
  • 13
  • 23
2

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')
    })
})
ckeeney
  • 1,270
  • 13
  • 18
0

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() )
Schnitter
  • 192
  • 3
  • 6