2

im Starting with puppeeteer and now at a point where I have a question:

Im on a site and when clicking on a button the server sends an ajax request to the server and brings a message on the homepage. I want to evaluate the answer e.g.:

wait newPage.click('#myButton'); //here the ajax request is triggered, now im looking for something like:
if("AJAXRESPONSE" != "This is the correct answer") {
//Throw error here
}
else {
//continue
}

Example

hardkoded
  • 18,915
  • 3
  • 52
  • 64
Farbkreis
  • 604
  • 3
  • 12
  • Does this answer your question? [puppeteer: Access JSON response of a specific request as in the network tab of DevTools](https://stackoverflow.com/questions/56514308/puppeteer-access-json-response-of-a-specific-request-as-in-the-network-tab-of-d) – Thomas Dondorf Apr 23 '20 at 16:06
  • Thanks; will figure it out tomorrow at my work – Farbkreis Apr 23 '20 at 16:52

1 Answers1

1

You can use the response event and try to infer what is the network response of your Ajax call. You can't be 100% sure on which event triggered a network response so you need to add some flags and being specific on the URL to check.

let resolve;
page.on('response', async response => {
  // We are going to use `resolve` as a flag.
  // We are going to assign `resolve` as closed as the click as possible
  if(resolve && response.url() === 'Your Ajax URL')
     resolve(await response.json());
});

var promise = new Promise(x => resolve = x);
await newPage.click('#myButton');

var output = await promise;
console.log(output);
hardkoded
  • 18,915
  • 3
  • 52
  • 64