Use await page.waitForSelector('#element') instead of time-based delays

How do I make the page wait until it is loaded using Puppeteer? Below is where I am facing the issue.

I’m working on creating a PDF from a single-page application using Puppeteer. Despite trying various suggestions from waitForNavigation doesn't work after clicking a link · Issue #1412 · puppeteer/puppeteer · GitHub, I can’t generate the PDF without using delays like await page.waitFor(2000). The page has dynamic content, including charts. How can I generate the PDF as soon as the page is fully loaded without relying on time-based delays? Here’s my current code:

const browser = await puppeteer.launch({ executablePath: ‘C:\Program Files (x86)\Google\Chrome\Application\chrome.exe’, ignoreHTTPSErrors: true, headless: true, devtools: false, args: [‘–no-sandbox’, ‘–disable-setuid-sandbox’] });

const page = await browser.newPage();

await page.goto(fullUrl, { waitUntil: ‘networkidle2’ });

await page.type(‘#username’, ‘scott’); await page.type(‘#password’, ‘tiger’);

await page.click(‘#Login_Button’);

// Need a solution here to wait for the page to load completely without using time-based delays

await page.pdf({ path: outputFileName, displayHeaderFooter: true, headerTemplate: ‘’, footerTemplate: ‘’, printBackground: true, format: ‘A4’ });

Any help will be appreciated.

Hey Kusha,

To generate a PDF without using time-based delays, you can utilize page.waitForNavigation() after clicking the login button. This ensures that the new page fully loads before creating the PDF. If there’s specific dynamically generated content you want to include, consider using page.waitForSelector() for that element:

const browser = await puppeteer.launch({ executablePath: ‘C:\Program Files (x86)\Google\Chrome\Application\chrome.exe’, ignoreHTTPSErrors: true, headless: true, devtools: false, args: [‘–no-sandbox’, ‘–disable-setuid-sandbox’] });

const page = await browser.newPage();

await page.goto(fullUrl, { waitUntil: ‘networkidle0’, });

await page.type(‘#username’, ‘scott’); await page.type(‘#password’, ‘tiger’);

await page.click(‘#Login_Button’);

await page.waitForNavigation({ waitUntil: ‘networkidle0’, });

// If there’s specific content to wait for, use page.waitForSelector // Example: await page.waitForSelector(‘#example’, { visible: true });

await page.pdf({ path: outputFileName, displayHeaderFooter: true, headerTemplate: ‘’, footerTemplate: ‘’, printBackground: true, format: ‘A4’, });