Farbkreis
Farbkreis

Reputation: 644

Evaluate AJAX Response in Puppeteer

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

Upvotes: 2

Views: 2763

Answers (1)

hardkoded
hardkoded

Reputation: 21647

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);

Upvotes: 1

Related Questions