How can I wait for a page to load after submitting a form with Puppeteer?

How can I wait for a page to load after submitting a form with Puppeteer? I use the following code to submit the form:

await page.click("button[type=submit]");

I want to wait for the new page to fully load before taking a screenshot. I prefer not to use a fixed timeout like this:

await page.waitFor(1 * 1000); //← unwanted workaround

How can I use Puppeteer to wait for the page to load before taking a screenshot?

Hi,

You can use page.waitForNavigation() to wait for the page to navigate to the new URL after form submission:

await Promise.all([
  page.click("button[type=submit]"),
  page.waitForNavigation({ waitUntil: 'networkidle0' }) // Wait for the network to be idle
]);
await page.screenshot({ path: 'example.png' });

This approach waits for the navigation to complete and ensures that the network is idle, indicating that the page has finished loading.

If you know a specific element that appears after the page loads, you can use page.waitForSelector() to wait for that element:

await page.click("button[type=submit]");
await page.waitForSelector('selector-for-element-that-appears-after-load'); // Replace with the actual selector
await page.screenshot({ path: 'example.png' });

This method waits until the specified element is present in the DOM, implying that the page has loaded.

You can also use waitUntil: ‘networkidle0’ with page.waitForNavigation() to wait until there are no more than 0 network connections for at least 500 ms:

await Promise.all([
  page.click("button[type=submit]"),
  page.waitForNavigation({ waitUntil: 'networkidle0' }) // Wait for the network to be idle
]);
await page.screenshot({ path: 'example.png' });

This approach ensures that the page has completed all network requests before proceeding with the screenshot.