How do I handle pop-ups and alerts with Headless Chromium?

When using Headless Chromium, you may encounter pop-ups and alerts that need to be handled programmatically since there's no user interface to interact with. Here's how you can handle these elements using Puppeteer in JavaScript and Selenium WebDriver in Python.

Handling Pop-ups and Alerts with Puppeteer (JavaScript)

In Puppeteer, you can listen for the dialog event and then use the accept or dismiss methods to interact with the alert, prompt, or confirm dialog.

Here's an example using Puppeteer in JavaScript:

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch({ headless: true });
    const page = await browser.newPage();

    // Listen for the "dialog" event before triggering the alert
    page.on('dialog', async dialog => {
        await dialog.accept(); // Use dialog.dismiss() if you want to cancel the alert

    await page.goto(''); // Replace with the URL where the alert occurs

    // Code to trigger the alert, for example, a button click
    // await'#alertButton');

    // Other actions...

    await browser.close();

Handling Pop-ups and Alerts with Selenium WebDriver (Python)

In Selenium WebDriver, you can interact with alerts by switching to the alert context and then accepting or dismissing it. Here's how you can do it using Python:

from selenium import webdriver
from import Options
from selenium.webdriver.common.alert import Alert

# Set up Chrome with headless option
chrome_options = Options()
driver = webdriver.Chrome(options=chrome_options)

driver.get('')  # Replace with the URL where the alert occurs

# Code to trigger the alert, for example, a button click
# driver.find_element_by_id('alertButton').click()

    # Switch to the alert
    alert = Alert(driver)

    # Print the text of the alert

    # Accept the alert (clicks OK)

    # To dismiss the alert (clicks Cancel), use:
    # alert.dismiss()

    # No alert was present
    print("No alert present.")

# Other actions...


Both examples assume that you have the necessary packages installed (puppeteer for the JavaScript example and selenium for the Python example) and that you have the appropriate drivers installed (e.g., chromedriver for Selenium with Chrome).

Remember, handling pop-ups and alerts requires that the code to handle the dialog is set up before the action that triggers the dialog. In headless mode, dialogs can interrupt the normal flow of automation, so they must be handled promptly to avoid timeouts and other errors.

Related Questions

Get Started Now

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