What leads Puppeteer to emit 'UnhandledPromiseRejectionWarning: Error: Navigation failed because browser has disconnected!'?

I’ve built a Node.js tool using Puppeteer (v1.11.0) to capture screenshots from various websites, but an issue with my async/await implementation is triggering the error “UnhandledPromiseRejectionWarning: Error: Navigation failed because browser has disconnected!”. Below is my revised code sample:

const browserAutomation = require('puppeteer');

const websites = {
  alpha: 'https://www.example.com',
  beta: 'https://www.sample.org'
};

browserAutomation.launch({ headless: true }).then(async (browserInstance) => {
  async function captureScreenshot(siteKey) {
    const siteURL = websites[siteKey];
    return new Promise(async (resolve, reject) => {
      const tab = await browserInstance.newPage();
      await tab.setViewport({ width: 1280, height: 800 });
      
      tab.once('console', async () => {
        await tab.pdf({
          path: `${siteKey}_output.pdf`,
          printBackground: true
        });
        await tab.close();
        resolve();
      });
      
      await tab.goto(siteURL, { waitUntil: ['domcontentloaded', 'networkidle0'] });
    });
  }

  async function processWebsites() {
    for (let key in websites) {
      if (websites.hasOwnProperty(key)) {
        await captureScreenshot(key);
      }
    }
    await browserInstance.close();
  }

  processWebsites();
});

The error may be triggered by a timing issue caused by mismanagement of asynchronous operations, leading to scenarios where the device disconnects before the promise resolves. From my experience, ensuring that all promises are either awaited or properly caught using try/catch is imperative. In my projects, added explicit timeouts and used detailed error logging to prevent indefinite waits, which otherwise caused browser disconnections. This approach helped in debugging the issue and handling unexpected delays that ultimately led to the navigation failure.

i think the issue stems from a faulty event timing since you’re calling goto then waiting for a console event. you might try a try/catch around navigation and a different method to wait for page render. it fixed similar race condition hiccups for me.