How to click the 'Ok' button inside an alert window with a Selenium command?

SeleniumAutomation TestingTesting Tools

We can click the OK button inside an alert window with Selenium webdriver. An alert is designed on a webpage to notify users or to perform some actions on the alert. It is designed with the help of Javascript.

An alert can be of three types – prompt, confirmation dialogue box or alert. Selenium has multiple APIs to handle alerts with an Alert interface. To click on the Ok button on alert, first of all we have to switch to alert with switchTo().alert() method.

Next, to click on the Ok button, we have to use accept() method. Please note we cannot identify elements on alert by inspecting on them. Also, there is no way to create a customized xpath for an alert.

Let us work with a sample alert having OK and Cancel buttons. We have to import org.openqa.selenium.Alert in our code to work with alerts.

Example

Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
public class AlertAccept{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      driver.findElement(By.xpath("//button[@name='submit']")).click();
      // Alert interface and switchTo().alert() method
      Alert al = driver.switchTo().alert();
      // click on OK to accept with accept()
      al.accept();
      driver.quit();
   }
}
raja
Published on 28-Aug-2020 16:39:54
Advertisements