Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert handling in Selenium WebDriver (selenium 2) with Java

I want to detect whether an alert is popped up or not. Currently I am using the following code:

    try {         Alert alert = webDriver.switchTo().alert();          // check if alert exists         // TODO find better way         alert.getText();          // alert handling         log().info("Alert detected: {}" + alert.getText());         alert.accept();     } catch (Exception e) {     } 

The problem is that if there is no alert on the current state of the web page, it waits for a specific amount of time until the timeout is reached, then throws an exception and therefore the performance is really bad.

Is there a better way, maybe an alert event handler which I can use for dynamically occurring alerts?

like image 703
Alp Avatar asked Nov 23 '11 15:11

Alp


People also ask

How many types of alerts are there in Selenium?

There are mainly 3 types of Alerts, namely: Simple Alert. Prompt Alert. Confirmation Alert.

What is the alert syntax in Selenium?

An alert can be of three types – a prompt which allows the user to input text, a normal alert and a confirmation alert. By default, the webdriver can only access the main page, once an alert comes up, the method switchTo(). alert() is used to shift the focus webdriver control to the alert.

How do I switch to alerts in Selenium?

To switch the control from the parent window to the Alert window, the Selenium WebDriver provides the following command: driver. switchTo( ). alert( );


1 Answers

This is what worked for me using Explicit Wait from here WebDriver: Advanced Usage

public void checkAlert() {     try {         WebDriverWait wait = new WebDriverWait(driver, 2);         wait.until(ExpectedConditions.alertIsPresent());         Alert alert = driver.switchTo().alert();         alert.accept();     } catch (Exception e) {         //exception handling     } } 
like image 110
Leo Avatar answered Sep 22 '22 20:09

Leo