ScreenshotNeo

BlogHow-to

How to Capture a Page Screenshot with Selenium After Accepting a JavaScript Alert

Accept a JavaScript alert before capturing the page with Selenium. See runnable Python and Java examples, common fixes, and a browser-free alternative.

By the ScreenshotNeo team4 October 20267 min read

To capture a page after a JavaScript alert, first handle the alert through WebDriver’s alert API, then take the screenshot from the driver. In Python, wait for the alert and call alert.accept(); in Java, call driver.switchTo().alert().accept(). A JavaScript alert is a native browser dialog, not a page element you can locate with CSS.

Python: wait for the alert, accept it, and save a screenshot

This complete example opens a page, triggers an alert with JavaScript, waits for the dialog, accepts it, and saves a screenshot of the current browser context:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
# Uncomment to run without opening a visible browser window.
# options.add_argument("--headless=new")

driver = webdriver.Chrome(options=options)
try:
    driver.get("https://example.com")

    # Demonstration trigger. In your test, replace this with the UI action
    # that causes the application to display its alert.
    driver.execute_script("window.alert('Continue?')")

    alert = WebDriverWait(driver, 10).until(EC.alert_is_present())
    print("Alert text:", alert.text)
    alert.accept()

    saved = driver.save_screenshot("page.png")
    if not saved:
        raise RuntimeError("WebDriver did not save the screenshot")
finally:
    driver.quit()

The wait is useful when the alert appears after an asynchronous action. If your code itself immediately triggers the alert, the wait still makes the expected browser state explicit. The screenshot is taken only after accept() has returned.

Triggering an alert through a page control

Usually, the alert appears after clicking a button or completing another action. Perform that action before waiting:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# driver has already navigated to the application page
driver.find_element(By.ID, "show-alert").click()
alert = WebDriverWait(driver, 10).until(EC.alert_is_present())
alert.accept()
driver.save_screenshot("after-alert.png")

Replace show-alert with a locator that matches your page. If clicking the control itself fails because an alert is already open, handle the alert that is currently blocking the page before issuing more page commands.

Dismiss, inspect, or enter text

  • alert.text reads the dialog message.
  • alert.accept() accepts an alert or confirmation dialog.
  • alert.dismiss() dismisses a confirmation dialog.
  • For a prompt that accepts input, call alert.send_keys("value") before accepting it.

Choose the action that matches the application behavior you need to test. Sending text applies to prompts, not ordinary alert dialogs.

Java: accept the alert and write the screenshot to a file

This Selenium Java example uses WebDriverWait to wait for the alert and TakesScreenshot to capture the current browsing context. It uses Java 11 or later for Files.copy:

import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;

import org.openqa.selenium.Alert;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class AlertScreenshot {
    public static void main(String[] args) throws Exception {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com");

            // Demonstration trigger; replace with the action in your test.
            ((org.openqa.selenium.JavascriptExecutor) driver)
                .executeScript("window.alert('Continue?')");

            Alert alert = new WebDriverWait(driver, Duration.ofSeconds(10))
                .until(ExpectedConditions.alertIsPresent());
            System.out.println("Alert text: " + alert.getText());
            alert.accept();

            Path screenshot = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE).toPath();
            Files.copy(screenshot, Path.of("page.png"));
        } finally {
            driver.quit();
        }
    }
}

For an existing alert that is already present, the essential sequence is driver.switchTo().alert().accept(), followed by the screenshot call. The screenshot file returned by Selenium may be temporary, so copy it to the destination you want to keep.

Reliable ordering and screenshot scope

  1. Navigate to the page and perform the action that opens the dialog.
  2. Wait for the alert to be present, unless the triggering operation is deliberately synchronous and immediate handling is appropriate.
  3. Read its text if the test needs to verify the message.
  4. Accept or dismiss it according to the test scenario.
  5. Capture the screenshot and verify that the file was written.

Selenium’s screenshot operation captures the current browsing context. Do not assume that every browser and driver returns a full-page image; check the behavior of the specific driver you use if content below the viewport must be included. The alert itself is a separate browser dialog, so the page screenshot should be requested after it has been handled.

Options and edge cases

Use an explicit wait when timing varies

An explicit wait for alert presence avoids guessing how long the application takes to show the dialog. Set the timeout to match the expected behavior of your application and test environment. If no dialog appears before the timeout, investigate the trigger and whether the page actually uses a native JavaScript dialog.

Confirm the dialog type

WebDriver’s alert API applies to JavaScript alerts, confirms, prompts, and certain beforeunload prompts. An HTML modal, cookie banner, browser permission prompt, or operating-system dialog is a different interface and cannot be handled as a JavaScript alert. Locate and interact with an HTML modal as page content instead.

Handle beforeunload separately

Selenium documentation says recent drivers automatically dismiss beforeunload prompts by default. That behavior is specific to beforeunload prompts; verify the driver’s behavior and applicable settings if your test depends on leaving a page with unsaved changes.

Choose screenshot output deliberately

Python’s save_screenshot(path) writes an image file and returns whether the save succeeded. In Java, getScreenshotAs(OutputType.FILE) returns a file that your code should copy to a stable destination. Ensure the destination directory exists and that the process can write to it.

Troubleshooting

Symptom Likely cause Fix
NoAlertPresentException The alert has not appeared, was already handled, or the UI is not a native JavaScript dialog. Wait for alert presence after the triggering action. Confirm the page opens a JavaScript alert rather than an HTML overlay or browser permission UI.
The click or next WebDriver command fails while a dialog is open The native alert is blocking normal page interaction. Switch to the alert and accept or dismiss it before sending more page commands.
The screenshot shows the page before the expected state The screenshot was requested before the alert was handled or before the application finished updating. Accept the alert first. If page content changes asynchronously afterward, wait for a page-specific condition before capturing.
No screenshot file appears The path is not writable, its parent directory is missing, or the save result was ignored. Use an absolute or known writable path, create the directory, and check the return value or copy operation.
The screenshot only contains the visible viewport The driver’s screenshot implementation captures the current viewport. Check the browser-driver behavior and use a supported full-page strategy if the entire document is required.
Alert wait times out The action did not trigger the dialog, the dialog is delayed, or the page uses a different UI element. Verify the trigger and locator, inspect the application behavior, and adjust the wait only when the page legitimately needs more time.

Performance, reliability, and cost

A local Selenium screenshot requires a browser session and a working browser driver. Keep the session alive until after the screenshot is saved, and close it in a finally block so failures do not leave a browser process behind. Avoid fixed sleeps when an explicit condition can express the state you are waiting for. Screenshot latency and output dimensions depend on the page, browser, driver, and environment; there is no single reliable timing or compatibility figure for this workflow.

This Selenium approach uses your own browser execution environment. If you need a managed screenshot endpoint instead, ScreenshotNeo offers a one-request screenshot API and an MCP server for AI agents. Its billing rules and plan prices are listed below.

Or skip the browser setup

For an ordinary page screenshot, call the ScreenshotNeo API with a URL. It returns an image or PDF; this URL-based call does not perform your Selenium alert interaction.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
  • Cookie banners, newsletter popups, and chat widgets are removed before the screenshot; each cleanup step can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Responses identify the page verdict and billing status in headers.
  • An MCP server lets AI agents use screenshot, page-information, and PDF-capture tools.
  • 1,000 screenshots a month are free with no card. Paid plans start at $5 for 3,000 screenshots; every feature is on every plan.

See ScreenshotNeo and the API documentation. Sign up for 1,000 free screenshots a month with no card.

FAQ

Can Selenium take a screenshot while an alert is still open?

Handle the alert first, then request the page screenshot. WebDriver’s alert context and the page’s browsing context are separate.

Can I use a CSS selector to accept a JavaScript alert?

No. A native JavaScript alert is not a DOM element. Use WebDriver’s alert API.

Does accepting the alert guarantee a full-page screenshot?

No. Accepting handles the dialog; screenshot dimensions and full-page behavior depend on the browser and driver implementation.

Can the screenshot include the alert message?

The page screenshot is captured from the browsing context after the dialog is handled. If you need to preserve the message for a test record, read and save alert.text separately.

Official Selenium references