Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium NoAlertPresentException

I'm trying to handle dialog (Ok Cancel type) with selenium WebDriver. So my aim is to click "Ok" button.

Scenario is:

  1. Click button for invoking dialog

    button.click();

  2. Try to accept

    webDriver.switchTo().alert().accept();

But I'm always getting NoAlertPresentException and seeing that dialog closes almost immediately. It seems to me that Selenium automatically closes dialog and when I want to accept, there is nothing to accept.

I'm sorry for my bad English.

like image 987
Matim Avatar asked Jul 19 '13 14:07

Matim


2 Answers

The usual cause of this issue is that Selenium is too quick and tries to accept an alert that has not yet been opened by the browser. This can be simply fixed by an explicit wait:

button.click();
WebDriverWait wait = new WebDriverWait(driver, 5);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
like image 174
Petr Janeček Avatar answered Nov 03 '22 02:11

Petr Janeček


Step 1:
    public boolean isAlertPresent(){
            boolean foundAlert = false;
            WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
            try {
                wait.until(ExpectedConditions.alertIsPresent());
                foundAlert = true;
                System.out.println("isAlertPresent : " +foundAlert);
            } catch (TimeoutException eTO) {
                foundAlert = false;
                System.out.println("isAlertPresent : " +foundAlert);
            }
            return foundAlert;
        }

Step 2:
public boolean tocheck_POP_Dialog()
    {   Alert alert;
        try
        {   
            alert=driver.switchTo().alert();


        }
        catch(NoSuchElementException elementException)
        {   
            return false;
        }

        alert.accept(); //Close Alert popup


        return true;
    }




Step 3 :
if(dummyPage.isAlertPresent())
                {
                    dummyPage.tocheck_POP_Dialog();
                }
like image 20
akhilesh gulati Avatar answered Nov 03 '22 02:11

akhilesh gulati