21

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

Normally it runs fine, but sometimes I get 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 received:

org.openqa.selenium.NoAlertPresentException 

I am attaching the screenshots of the alert: First Alert and by using esc or enter i gets the second alertSecond Alert

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

Shantanu Nandan
  • 1,438
  • 8
  • 30
  • 56
  • Could this be the root cause? A bypassed call to fxdriver.modals.clearFlag_ ... cf. https://stackoverflow.com/questions/44568402/how-do-i-manually-mouse-dismiss-a-javascript-alert-and-get-back-the-the-body-o/44592827#44592827 – NevilleDNZ Jun 16 '17 at 23:57
  • It is weird how a question on ChromeDriver has FirefoxDriver solutions. Does that mean that chrome has no way to overcome this default behaviour. – Naveen Dennis Aug 10 '18 at 18:49

11 Answers11

35

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();
    }
}
RotS
  • 2,142
  • 2
  • 24
  • 30
  • 3
    If the default behavior of the driver was to accept all alerts then why did it throw an exception in the first place? Shouldn't it have automatically accepted the alert and continued? – Mugen May 27 '20 at 06:24
  • maybe to ensure that the developer is aware of the alert being opened? – RotS May 28 '20 at 14:25
  • Which means it is not clicking on the alert in spite of the setting. – Mugen May 30 '20 at 13:07
  • Why does this occur? What's the reason behind such alerts occurring intermittently? – Archis Thakkar Jan 12 '21 at 07:40
5

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.

Sudara
  • 4,769
  • 3
  • 34
  • 39
1

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.
}
shri046
  • 1,148
  • 11
  • 12
1
UnhandledAlertException 

is thrown when it encounters an unhanded alert box popping out. You need to set your code to act normally unless an alert box scenario is found. This overcomes your problem.

       try {
            System.out.println("Opening page: {}");
            driver.get({Add URL});
            System.out.println("Wait a bit for the page to render");
            TimeUnit.SECONDS.sleep(5);
            System.out.println("Taking Screenshot");
            File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            String imageDetails = "C:\\images";
            File screenShot = new File(imageDetails).getAbsoluteFile();
            FileUtils.copyFile(outputFile, screenShot);
            System.out.println("Screenshot saved: {}" + imageDetails);
        } catch (UnhandledAlertException ex) {
            try {
                Alert alert = driver.switchTo().alert();
                String alertText = alert.getText();
                System.out.println("ERROR: (ALERT BOX DETECTED) - ALERT MSG : " + alertText);
                alert.accept();
                File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                String imageDetails = "C:\\Users";
                File screenShot = new File(imageDetails).getAbsoluteFile();
                FileUtils.copyFile(outputFile, screenShot);
                System.out.println("Screenshot saved: {}" + imageDetails);
                driver.close();
            } catch (NoAlertPresentException e) {
                e.printStackTrace();
            }
        } 
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
0

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();

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

You can use UnexpectedAlertBehaviour.ACCEPT or UnexpectedAlertBehaviour.DISMISS

Brandon Minnick
  • 13,342
  • 15
  • 65
  • 123
0

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.

Sobhit Sharma
  • 697
  • 14
  • 45
0

I tried this below code, it perfectly worked for me (Chrome)

try{
    System.out.println("Waiting for Alert");
    WebDriverWait wait = new WebDriverWait(driver,10);
    wait.until(ExpectedConditions.alertIsPresent()).dismiss();
    System.out.println("Alert Displayed");
}
catch (Exception e){
    System.out.println("Alert not Displayed");
}
-1

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));
      }
Vivek Singh
  • 3,641
  • 2
  • 22
  • 27
-1

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();
}
Mubashar
  • 12,300
  • 11
  • 66
  • 95
-1

The below code will help to handle unexpected alerts in selenium

try{
} catch (Exception e) {
if(e.toString().contains("org.openqa.selenium.UnhandledAlertException"))
 {
    Alert alert = getDriver().switchTo().alert();
    alert.accept();
 }
}