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