How to handle pop-ups and modals in Puppeteer?

Handling pop-ups and modals in Puppeteer, a Node.js library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol, can be quite straightforward once you understand the basics of how Puppeteer works.

The key methods to handle pop-ups and modals are page.waitForSelector, page.on and page.click.

Here's an example of how to handle a JavaScript alert:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  page.on('dialog', async dialog => {
    console.log(dialog.message());
    await dialog.dismiss();
  });

  await page.goto('https://your-url.com');

  // This line will trigger the alert on the page.
  await page.evaluate(() => alert('This is my message'));

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

In this example, page.on('dialog' is a Puppeteer event that listens for Dialogs (JavaScript alerts, prompts, confirms). When a dialog appears, it will print the dialog message in the console and then dismiss the dialog.

To handle a modal, you usually have to interact with it as if it were a part of the webpage. Here's an example of how to handle a modal by clicking a close button:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto('https://your-url.com');

  // This will wait for the element with the selector of '#close-button' to appear in page.
  await page.waitForSelector('#close-button');

  // This will 'click' on the close button of the modal.
  await page.click('#close-button');

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

In this example, page.waitForSelector('#close-button') waits for the element with the selector of #close-button to appear in the page. page.click('#close-button') will 'click' on that close button, usually causing the modal to close.

Remember that the selectors used (#close-button and #close-button) should be replaced with the actual selectors of the elements you want to interact with on your web page.

It's also important to note that Puppeteer's operations are asynchronous, so be sure to handle them appropriately in your code, for example by using async/await as in the examples above.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon