Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 599
Alex29 Avatar asked Aug 22 '17 15:08

Alex29


3 Answers

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

like image 108
Reniks Avatar answered Nov 18 '22 01:11

Reniks


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);
like image 14
storenth Avatar answered Nov 18 '22 01:11

storenth


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();
like image 6
Ilya Zub Avatar answered Nov 18 '22 02:11

Ilya Zub