
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Click OK Button Inside Alert Window with Selenium Command
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(); } }