javascriptnode.jspuppeteer

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


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


Solution

  • 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'
    ]);