18

How can I wait for network idle after click on an element in puppeteer?

const browser = await puppeteer.launch({headless: false});
await page.goto(url, {waitUntil: 'networkidle'});

await page.click('.to_cart'); //Click on element trigger ajax request
//Now I need wait network idle(Wait for the request complete)
await page.click('.to_cart');

UPD: No navigation after the element was clicked

Serhii Shliakhov
  • 2,631
  • 3
  • 19
  • 37

3 Answers3

9

I ran into a similar issue and found the workaround function on the Puppeteer Control networkidle wait time issue to suit my needs: https://github.com/GoogleChrome/puppeteer/issues/1353#issuecomment-356561654

Essentially, you can create a custom function, and call that prior to any additional steps:

function waitForNetworkIdle(page, timeout, maxInflightRequests = 0) {
  page.on('request', onRequestStarted);
  page.on('requestfinished', onRequestFinished);
  page.on('requestfailed', onRequestFinished);

  let inflight = 0;
  let fulfill;
  let promise = new Promise(x => fulfill = x);
  let timeoutId = setTimeout(onTimeoutDone, timeout);
  return promise;

  function onTimeoutDone() {
    page.removeListener('request', onRequestStarted);
    page.removeListener('requestfinished', onRequestFinished);
    page.removeListener('requestfailed', onRequestFinished);
    fulfill();
  }

  function onRequestStarted() {
    ++inflight;
    if (inflight > maxInflightRequests)
      clearTimeout(timeoutId);
  }

  function onRequestFinished() {
    if (inflight === 0)
      return;
    --inflight;
    if (inflight === maxInflightRequests)
      timeoutId = setTimeout(onTimeoutDone, timeout);
  }
}

// Example
await Promise.all([
  page.goto('https://google.com'),
  waitForNetworkIdle(page, 500, 0), // equivalent to 'networkidle0'
]);
Rob C
  • 662
  • 5
  • 15
1

There are two methods in Puppeteer docs.

Example:

await Promise.all([
    page.waitForRequest(callback), 
    page.waitForResponse(callback)
])
Farhad
  • 494
  • 5
  • 20
Naimur Rahman
  • 697
  • 4
  • 15
-3

Directly from the docs

This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly cause the page to navigate. Consider this example:

const [response] = await Promise.all([
  page.waitForNavigation(), // The promise resolves after navigation has finished
  page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
]);
NoriSte
  • 3,589
  • 1
  • 19
  • 18