--------------------------------------------------------------------------------------------------------------------------
Confirmation Alert
This alert comes with an option to accept or dismiss the alert. To accept the alert you can use Alert.accept() and to dismiss you can use the Alert.dismiss().
Code:
package alert;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ConfirmationAlert {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "D:\\vishal\\selenium\\chromedriver_win32\\dasdf\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("http://toolsqa.com/handling-alerts-using-selenium-webdriver/");
WebElement confirmationalert=driver.findElement(By.xpath("html/body/div[1]/div[5]/div[2]/div/div/p[8]/button"));
confirmationalert.click();
Alert alert=driver.switchTo().alert();
String message=alert.getText();
System.out.println("Alert="+message);
alert.accept();
//you also use alert.dismiss() comand for alert
driver.close();
}
}
------------------------------------------------------------------------------------------------------
Prompt Alerts
In prompt alerts you get an option to add text to the alert box. This is specifically used when some input is required from the user. We will use the sendKeys() method to type something in the Prompt alert box. Here is the code
Code:
package alert;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class PromptAlert {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "D:\\vishal\\selenium\\chromedriver_win32\\dasdf\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("http://toolsqa.com/handling-alerts-using-selenium-webdriver/");
WebElement promptalert=driver.findElement(By.xpath("html/body/div[1]/div[5]/div[2]/div/div/p[11]/button"));
promptalert.click();
Alert alert=driver.switchTo().alert();
//for entering message
driver.switchTo().alert().sendKeys("say hello");
String message=alert.getText();
System.out.println("Alert="+message);
alert.accept();
//you also use alert.dismiss() comand for alert
driver.close();
}
}