Handling Alerts in Selenium WebDriver

Alerts can be handled in selenium webdriver using the Alert class. Users can refer to the alert and confirm box in this sample webpage. Click on "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.

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
	//Handling alert boxes
	//Click on generate alert button
	driver.findElement(By.cssSelector("div#AlertBox button")).click();
	//Using Alert class to first switch to or focus to the alert box
	Alert alert = driver.switchTo().alert();
	//Using accept() method to accep the alert box
	//Handling confirm box
	//Click on Generate Confirm Box
	driver.findElement(By.cssSelector("div#ConfirmBox button")).click();
	Alert confirmBox = driver.switchTo().alert();
	//Using dismiss() command to dismiss the confirm box
	//Similarly accept can be used to accept the confirm box