handling alerts in selenium webdriver

Handling Alerts in Selenium WebDriver

Last updated on

Alerts can be handled in Selenium WebDriver using the Alert interface. Users can refer to the alert and confirm box in this sample webpage

Click on the “Generate Alert Box” and “Generate Confirm Box” buttons to generate the alert and confirm boxes. The script below will first generate alert boxes by clicking on these buttons and use alert class methods to accept/dismiss them.


Sample Script – Alerts in Selenium

public void alertAutomation() throws InterruptedException{
	
	//Create firefox driver's instance
	WebDriver driver = new FirefoxDriver();
						
	//Set implicit wait of 10 seconds
	driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
				
	//Launch sampleSiteForSelenium
	driver.get("https://artoftesting.com/samplesiteforselenium");
						
	//Handling alert boxes
	//Click on generate alert button
	driver.findElement(By.cssSelector("div#AlertBox button")).click();
		
	Thread.sleep(3000);
		
	//Using Alert class to first switch to or focus to the alert box
	Alert alert = driver.switchTo().alert();
		
	//Using accept() method to accept the alert box
	alert.accept();
		
	//Handling confirm box
	//Click on Generate Confirm Box
	driver.findElement(By.cssSelector("div#ConfirmBox button")).click();
		
	Thread.sleep(3000);
		
	Alert confirmBox = driver.switchTo().alert();
		
	//Using dismiss() command to dismiss the confirm box
	//Similarly accept can be used to accept the confirm box
	confirmBox.dismiss();
}

That’s all we have in this post, comment below if you have any queries. Also please share this post with your friends and don’t forget to check our complete selenium tutorial here.

Selenium Complete Step-by-Step Tutorial

4 thoughts on “Handling Alerts in Selenium WebDriver”

Leave a Comment