Search code examples
javaselenium-webdriveralertpopupwindow

How to handle the Selenium Pop-up with java


I tried several options to handle the Pop-up with Selenium and fill the field values. But it does not work with the below code.

Selenium java code:

driver.findElement(By.xpath("//*[@id=\"loginBox\"]/div[2]/div/div/div[1]/div")).click();
Thread.sleep(2000);

Alert alert = driver.switchTo().alert();
Thread.sleep(3000);

driver.findElement(By.name("Email")).sendKeys("xxx@yyy.com");
Thread.sleep(2000);

alert.accept();

HTML :

<div class="content">
 <form class="ui form">
  <div class="field">
   <label for="Email">Email</label>
    <div view="horizontal" class="ui right corner labeled input">
     <div class="ui label label right corner">
      <i aria-hidden="true" class="asterisk icon">
      </i>
     </div><input name="Email" id="Email" placeholder="Please enter email address" type="email" value="">
    </div>
   </div>
  • How can I handle the Pop-up and fill the field?
  • Also, in the end how do I close the alert window?

Solution

  • The pop-up is HTML element, not a modal dialog to use driver.switchTo().alert().
    To enter email you have to wait for the element, and for that sleep bad choice. Code below waiting for visibility of the email using WebDriverWait, it's best practice.
    Also, not a good practice to use //*[@id=\"loginBox\"]/div[2]/div/div/div[1]/div like selectors. You can find some helpful information about best practice for selectors here.

    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    // ...
    
    WebDriverWait wait = new WebDriverWait(driver, 10);
    
    driver.findElement(By.xpath("//*[@id=\"loginBox\"]/div[2]/div/div/div[1]/div")).click();
    
    WebElement email = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("Email")));
    email.sendKeys("xxx@yyy.com");
    email.submit();