Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

puppeteer wait for page update after button click (no navigation)

Trying puppeteer for the first time and it is amazing. I need to wait for a page to fetch and render new data after a button click. This does not cause a navigation (the url is the same) so the following code does not work (it gives timeout exception):

await Promise.all([
    myButton.click()
    page.waitForNavigation()
])

What's the correct way to wait for the page to fetch/render async data on click?

like image 518
revy Avatar asked Aug 23 '19 15:08

revy


2 Answers

Assuming the DOM changes in some way, you can wait for a specific element or selector.

Maybe an image appears.

await myButton.click();
await page.waitForSelector('img.success');

Maybe some element with an ID attribute is inserted into the DOM.

await myButton.click();
await page.waitForSelector('#newElementThatAppeared');

If you're unfamiliar with DOM selectors, you can read up here and here. They're powerful and easy to use.

Update - Custom wait predicate.

If we always know the length...

await myButton.click();
await page.waitFor(() => document.querySelectorAll('ul.specialList li').length > 5);

If we know the length will increase

const listSize = await page.evaluate(() => document.querySelectorAll('ul.specialList li').length);
await myButton.click();
await page.waitFor(() => document.querySelectorAll('ul.specialList li').length > listSize);
like image 112
Tom Faltesek Avatar answered Oct 30 '22 23:10

Tom Faltesek


First of all await Promise.all some kind of concurrency and if you need click and then wait split this with

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

And be noted:

This resolves when the page navigates to a new URL or reloads.

like image 34
storenth Avatar answered Oct 30 '22 23:10

storenth