org.openqa.selenium.UnhandledAlertException: unexpected alert open

I am using a Chrome Driver and trying to test a webpage.

Normally it runs fine but some time I gets exceptions--

 org.openqa.selenium.UnhandledAlertException: unexpected alert open
 (Session info: chrome=38.0.2125.111)
 (Driver info: chromedriver=2.9.248315,platform=Windows NT 6.1 x86) (WARNING: The server did not  provide any stacktrace information)
 Command duration or timeout: 16 milliseconds: null
 Build info: version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:30'
 System info: host: 'Casper-PC', ip: '10.0.0.4', os.name: 'Windows 7', os.arch: 'x86', os.version:  '6.1', java.version: '1.8.0_25'
 Driver info: org.openqa.selenium.chrome.ChromeDriver

Then i tried to handle the alert --

  Alert alt = driver.switchTo().alert();
  alt.accept();

But this time i recived-- org.openqa.selenium.NoAlertPresentException

I am attaching the screen shots of the alert-

I am not able to figure out what to do now. The problem is i am not receiving this exception always. And when it occurs then the test fails.

Answers


I had this problem too. It was due to the default behaviour of the driver when it encounters an alert. The default behaviour was set to "ACCEPT", thus the alert was closed automatically, and the switchTo().alert() couldn't find it.

The solution is to modify the default behaviour of the driver ("IGNORE"), so that it doesn't close the alert:

DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
d = new FirefoxDriver(dc);

Then you can handle it:

try {
    click(myButton);
} catch (UnhandledAlertException f) {
    try {
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        System.out.println("Alert data: " + alertText);
        alert.accept();
    } catch (NoAlertPresentException e) {
        e.printStackTrace();
    }
}

You can use Wait functionality in Selenium WebDriver to wait for an alert, and accept it once it is available.

In C# -

public static void HandleAlert(IWebDriver driver, WebDriverWait wait)
{
    if (wait == null)
    {
        wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
    }

    try
    {
        IAlert alert = wait.Until(drv => {
            try
            {
                return drv.SwitchTo().Alert();
            }
            catch (NoAlertPresentException)
            {
                return null;
            }
        });
        alert.Accept();
    }
    catch (WebDriverTimeoutException) { /* Ignore */ }
}

Its equivalent in Java -

public static void HandleAlert(WebDriver driver, WebDriverWait wait) {
    if (wait == null) {
        wait = new WebDriverWait(driver, 5);
    }

    try {
        Alert alert = wait.Until(new ExpectedCondition<Alert>{
            return new ExpectedCondition<Alert>() {
              @Override
              public Alert apply(WebDriver driver) {
                try {
                  return driver.switchTo().alert();
                } catch (NoAlertPresentException e) {
                  return null;
                }
              }
            }
        });
        alert.Accept();
    } catch (WebDriverTimeoutException) { /* Ignore */ }
}

It will wait for 5 seconds until an alert is present, you can catch the exception and deal with it, if the expected alert is not available.


Is your switch to alert within a try/catch block? You may also want to add a wait timeout to see if the alert shows up after a certain delay

try {
    // Add a wait timeout before this statement to make 
    // sure you are not checking for the alert too soon.
    Alert alt = driver.switchTo().alert();
    alt.accept();
} catch(NoAlertPresentException noe) {
    // No alert found on page, proceed with test.
}

After click event add this below code to handle

    try{
         driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
       }
 catch (org.openqa.selenium.UnhandledAlertException e) {                
         Alert alert = driver.switchTo().alert(); 
         String alertText = alert.getText().trim();
         System.out.println("Alert data: "+ alertText);
         alert.dismiss();}

... do other things driver.close();


DesiredCapabilities firefox = DesiredCapabilities.firefox();
firefox.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);

You can use UnexpectedAlertBehaviour.ACCEPT or UnexpectedAlertBehaviour.DISMISS


I was facing the same issue and I made this below changes.

try {
    click(myButton);
} catch (UnhandledAlertException f) {
    try {
        Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
        System.out.println("Alert data: " + alertText);
        alert.accept();
    } catch (NoAlertPresentException e) {
        e.printStackTrace();
    }
}

It worked amazingly.


You can try this snippet:

public void acceptAlertIfAvailable(long timeout)
      {
        long waitForAlert= System.currentTimeMillis() + timeout;
        boolean boolFound = false;
        do
        {
          try
          {
            Alert alert = this.driver.switchTo().alert();
            if (alert != null)
            {
              alert.accept();
              boolFound = true;
            }
          }
          catch (NoAlertPresentException ex) {}
        } while ((System.currentTimeMillis() < waitForAlert) && (!boolFound));
      }

Following is working for me

    private void acceptSecurityAlert() {

    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(10, TimeUnit.SECONDS)          
                                                            .pollingEvery(3, TimeUnit.SECONDS)          
                                                            .ignoring(NoSuchElementException.class);    
    Alert alert = wait.until(new Function<WebDriver, Alert>() {       

        public Alert apply(WebDriver driver) {

            try {

                return driver.switchTo().alert();

            } catch(NoAlertPresentException e) {

                return null;
            }
        }  
    });

    alert.accept();
}

Need Your Help

Diagnosing 404 errors on IIS 7 and ASP.NET MVC

asp.net asp.net-mvc iis iis-7 httphandler

I have an mvc app developed and tested with Cassini. Deployed to my site on GoDaddy, and the default page comes up fine. Click to log in, and I get a 404.

How to duplicate schemas in PostgreSQL

postgresql database-schema foreign-key-relationship postgresql-9.1

I have a database with schema public and schema_A. I need to create a new schema schema_b with the same structure than schema_a.