Jak zvládat upozornění a vyskakovací okna v Selenium?

⚡ Chytré shrnutí

Alerts and popups in Selenium jsou JavaScript dialogs and child windows that block automation flow. This article explains how to identify simple, prompt, and confirmation alerts, switch into them with WebDriver, and manage multiple windows using getWindowHandles().

  • 🔔 Základní definice: A Selenium alert is a JavaScript dialog rendered above the page that must be handled before further actions.
  • 🗂️ Three Alert Types: Simple (info), Prompt (text input), and Confirmation (Yes/No) each require different WebDriver calls.
  • 🛠️ Alert API: Use driver.switchTo().alert() with accept(), dismiss(), getText(), and sendKeys() to interact with the dialog.
  • 🪟 Window Handling: getWindowHandle() returns the current window ID; getWindowHandles() returns the full Set for switching.
  • ???? Selenium 4 Poznámka: Selenium Manager auto-resolves drivers, removing the need for hard-coded chromedriver.exe paths.
  • 🤖 Asistence AI: AI agents generate locator-aware alert and window scripts, reducing manual scaffolding in test suites.

Jak zvládat upozornění a vyskakovací okna v Selenium

What is an Alert in Selenium?

An Upozorněte Selenium je malý JavaScript dialog box that appears on the screen to give the user some information or notification. It can confirm a specific action, request permission to perform an operation, or display a warning message.

In this tutorial, you will learn how to handle popups in Selenium and the different types of alerts found in web application Testování. We will also see how to handle an alert in Selenium WebDriver and how to accept or reject it depending on the alert type.

Typy upozornění v Selenium

JavaScript exposes three alert dialogs that Selenium must handle differently.

1) Simple Alert

The simple alert displays information or a warning on screen. The user can only acknowledge it by clicking OK.

Simple alert dialog example in browser

2) Prompt Alert

The prompt alert asks the user for input. Selenium WebDriver can type into it using sendKeys("input...").

Prompt alert dialog with input field

3) Confirmation Alert

The confirmation alert asks the user to approve or cancel an operation. It exposes both OK a Zrušit Tlačítka.

Confirmation alert dialog with OK and Cancel buttons

How to Handle an Alert in Selenium webový ovladač

Jedno Alert interface in Selenium webový ovladač exposes four methods that cover every alert interaction.

  1. void dismiss() — clicks the Zrušit .
driver.switchTo().alert().dismiss();
  1. void accept() — clicks the OK .
driver.switchTo().alert().accept();
  1. Řetězec getText() — captures the alert message.
driver.switchTo().alert().getText();
  1. void sendKeys(String stringToSend) — types text into a prompt alert.
driver.switchTo().alert().sendKeys("Text");

Eclipse autocomplete shows the available alert methods after typing alert. on the editor line. Switch from the main window into the alert at any time using SeleniumJe .přepnout na() metoda.

Eclipse autocomplete showing alert handling methods

Worked Example: Delete Customer Demo

Let us automate the following scenario. We will use the Guru99 demo site to illustrate Selenium alert handling.

Krok 1) Launch the browser and open https://demo.guru99.com/test/delete_customer.php.

Krok 2) Enter any Customer ID.

Delete Customer demo page with Customer ID field

Krok 3) Klepněte na tlačítko Odeslat .

Submit button to trigger confirmation alert

Krok 4) Accept or dismiss the resulting confirmation alert.

Confirmation alert triggered by delete action

Selenium Java Code: Rukojeť Confirmation Alert

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.Alert;

public class AlertDemo {

    public static void main(String[] args) throws NoAlertPresentException, InterruptedException {
        // Selenium 4 ships Selenium Manager, so an explicit driver path is no longer required.
        WebDriver driver = new ChromeDriver();

        // Open the Delete Customer demo page
        driver.get("https://demo.guru99.com/test/delete_customer.php");

        driver.findElement(By.name("cusid")).sendKeys("53920");
        driver.findElement(By.name("submit")).submit();

        // Switch to the confirmation alert
        Alert alert = driver.switchTo().alert();

        // Capture the alert message
        String alertMessage = alert.getText();
        System.out.println(alertMessage);
        Thread.sleep(5000);

        // Accept the alert
        alert.accept();

        driver.quit();
    }
}

Výstup: The browser opens the Delete Customer page, submits the customer ID, accepts the confirmation alert, and removes the record from the demo application.

How to Handle Popup Windows in Selenium webový ovladač

When automation must work across multiple browser windows, the test has to switch focus between them and return to the parent window after each operation. Selenium WebDriver exposes two methods that make this possible.

driver.getWindowHandles()

Vrací Set<String> of every open window handle. Iterate over the set to switch from the main window to any child window in the application.

driver.getWindowHandle()

Vrací String with the unique handle of the current window. Capture this before opening any child window so you can return to the parent later.

Follow these steps to demonstrate window handling against the Guru99 popup demo.

Worked Example: Window Switching

Krok 1) Launch the browser and open https://demo.guru99.com/popup.php.

Guru99 popup demo landing page

Krok 2) Klepněte na tlačítko Klikněte zde link. A new child window opens.

Child window opening from the Click Here link

Krok 3) The child window prompts the user to enter an email ID and submit.

Child window email input form

Krok 4) Enter the email ID and submit.

Email submission inside the child window

Krok 5) The page displays the access credentials returned by the demo.

Access credentials displayed in the child window

After the credentials display:

  1. Close the child window.

Closing the child window in the browser

  1. Switch focus back to the parent window.

Switching focus back to the parent window

Selenium Java Code: Handle Multiple Windows

import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WindowHandle_Demo {

    public static void main(String[] args) throws InterruptedException {
        // Selenium 4 auto-resolves the browser driver via Selenium Manager
        WebDriver driver = new FirefoxDriver();

        driver.get("https://demo.guru99.com/popup.php");
        driver.manage().window().maximize();

        driver.findElement(By.xpath("//*[contains(@href,'popup.php')]")).click();

        String mainWindow = driver.getWindowHandle();

        // Capture every open window handle
        Set<String> allWindows = driver.getWindowHandles();
        Iterator<String> iterator = allWindows.iterator();

        while (iterator.hasNext()) {
            String childWindow = iterator.next();

            if (!mainWindow.equalsIgnoreCase(childWindow)) {
                // Switch to the child window
                driver.switchTo().window(childWindow);
                driver.findElement(By.name("emailid")).sendKeys("gaurav.3n@gmail.com");
                driver.findElement(By.name("btnLogin")).click();

                // Close the child window
                driver.close();
            }
        }
        // Return focus to the main window
        driver.switchTo().window(mainWindow);
        driver.quit();
    }
}

Výstup: The site launches, the Klikněte zde link opens a child tab, Selenium enters the email and submits, closes the child window, and returns to the parent.

Multiple window handling completed in Selenium

Závěr

  • Defined the three Selenium alert types — simple, prompt, and confirmation — with a screenshot for each.
  • Demonstrated alert handling with the WebDriver Alert interface using a working delete-customer scenario.
  • Handled multiple browser windows by capturing handles with getWindowHandle() a getWindowHandles() and switching between them.

Nejčastější dotazy

An alert is a native JavaScript dialog that suspends the page until handled. A popup window is a new browser window or tab. Alerts use switchTo().alert(); popups use switchTo().window() with the handle returned by getWindowHandles().

NoAlertPresentException is thrown when switchTo().alert() runs but no alert is currently displayed. Wrap the call with WebDriverWait until ExpectedConditions.alertIsPresent() is true to give the page time to trigger the dialog.

Basic-auth popups are not standard JavaScript alerts. Pass credentials in the URL (https://user:pass@site.com) or use Selenium 4 CDP Network.setExtraHTTPHeaders. For SSO popups, use BrowserStack or a registered hasAuthentication handler.

Asistenti s umělou inteligencí, jako například AI code copilots generate locator-aware alert handlers, predict required waits, and refactor brittle XPath. They also draft assertions for alert text and child window URLs, accelerating Selenium test creation.

Yes. Self-healing test platforms use AI to detect DOM changes, swap broken locators, and adjust waits when alerts or popups shift. This reduces maintenance for Selenium suites running against frequently updated front ends.

Shrňte tento příspěvek takto: