Search code examples
javascriptpdf-generationpuppeteergoogle-chrome-headless

Puppeteer wait until page is completely loaded


I am working on creating PDF from web page.

The application on which I am working is single page application.

I tried many options and suggestion on https://github.com/GoogleChrome/puppeteer/issues/1412

But it is not working

    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');
await page.waitFor(2000);

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

What I want is to generate PDF report as soon as Page is loaded completely.

I don't want to write any type of delays i.e. await page.waitFor(2000);

I can not do waitForSelector because the page has charts and graphs which are rendered after calculations.

Help will be appreciated.


Solution

  • You can use page.waitForNavigation() to wait for the new page to load completely before generating a PDF:

    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',
    });
    
    await page.pdf({
      path: outputFileName,
      displayHeaderFooter: true,
      headerTemplate: '',
      footerTemplate: '',
      printBackground: true,
      format: 'A4',
    });
    

    If there is a certain element that is generated dynamically that you would like included in your PDF, consider using page.waitForSelector() to ensure that the content is visible:

    await page.waitForSelector('#example', {
      visible: true,
    });