Selenium WebDriver with Java: Can't accept alert

亡梦爱人 提交于 2019-11-29 08:45:40

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.

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

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!