简体   繁体   中英

Selenium WebDriver with Java: Can't accept alert

When recording in selenium IDE I can click the "OK" button in a popup, and expected to be able to click it using

driver.findElement(By.linkText("OK")).click();

but this was not the case.

Similarly this doesn't work.

driver.switchTo().alert().accept();

Selenium throws a NoAlertPresent exception. If what's popping up is not an alert, then what is it? And how do I click yes!

in such case I'd prefer to check(verify) the alert presence on the page and then if is present - accept it. It be somthing like:

public boolean isAlertPresent() {

  boolean presentFlag = false;

  try {

   // Check the presence of alert
   Alert alert = driver.switchTo().alert();
   // Alert present; set the flag
   presentFlag = true;
   // if present consume the alert
   alert.accept();

  } catch (NoAlertPresentException ex) {
   // Alert not present
   ex.printStackTrace();
  }

  return presentFlag;

 }

here you can get details Also do not forget about debug step by step.

Hope this helps you.

It could be anything. You should be telling us that.

If it is a Java Script alert then, this should work

driver.switchTo().alert().accept();

At the very least you could try sending enter/return key stroke, if the "OK" button is autoselected/highlighted by the web app.

import org.openqa.selenium.Keys
WebElement.sendKeys(Keys.RETURN);

Update


It could also be because your alert is not present at the time you are trying to click/accept it. For a quick check put in a sleep of 4-5 seconds and then try driver.switchTo().alert().accept(); . Once it is ascertained, then put in a wait for alert present in a try and catch loop (any exception handling).

if you are using latest version of webdriver, infact anything above 2.20 then

driver.switchTo().alert().accept();

should work provided the alert is a javascript alert similar to the one we get when we click

alert demo OR confirm pop-up demo

Updated

here this code will help you accept the alert

driver = new FirefoxDriver();
String baseUrl = "http://www.w3schools.com/js/tryit.asp?filename=tryjs_alert";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl);
driver.switchTo().frame(0);
driver.findElement(By.cssSelector("input[type=\"button\"]")).click();
driver.switchTo().alert().accept();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM