Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in DevOps and Agile by (29.3k points)

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?

1 Answer

0 votes
by (50.2k points)

This problem got resolved with the following code, please go through the code

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

    }

}

This alert can be created with the help of explicit wait as shown in the above code.

Refer: https://www.seleniumhq.org/#explicit-and-implicit-waits

Browse Categories

...