How to wait for the page to load after form submission with Puppeteer and JavaScript?

Estimated read time 2 min read

You can wait for the page to load after form submission with Puppeteer and JavaScript using the page.waitForNavigation() method. This method waits for the next navigation event to occur, and it can be used to wait for a form submission to complete.

Here’s an example:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');

  // Submit the form
  await page.evaluate(() => {
    document.querySelector('form').submit();
  });

  // Wait for the next navigation event to occur
  await page.waitForNavigation();

  // Take a screenshot
  await page.screenshot({ path: 'example.png' });

  await browser.close();
})();

You can also use the page.waitForSelector() method to wait for a specific element to appear on the page after form submission. This can be useful if you need to wait for a specific element to be loaded before taking a screenshot or interacting with the page.

Here’s an example:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');

  // Submit the form
  await page.evaluate(() => {
    document.querySelector('form').submit();
  });

  // Wait for the specific element to appear on the page
  await page.waitForSelector('#result');

  // Take a screenshot
  await page.screenshot({ path: 'example.png' });

  await browser.close();
})();

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply