WebDriver.TargetLocator interface provides alert()
function, to handle the dialog boxes.
Alert
alert()
Switches to the currently active modal dialog for this
particular driver instance.
Alert interface provides following methods to work with
alert boxes.
Method
|
Description
|
void dismiss()
|
Used to cancel the alert box.
|
void accept()
|
Used to accept the alert box, equivalent to clicking the
OK button on alert box.
|
String getText()
|
Return the text appears on the dialog box.
|
void sendKeys(String keysToSend)
|
Send some information to alert box, if allowed.
|
void setCredentials(Credentials credentials)
|
Set credentials
|
void authenticateUsing(Credentials credentials)
|
Authenticate an HTTP Basic Auth dialog.
|
index.jsp
<!DOCTYPE html> <html> <body> <p>Click the button to display an alert box:</p> <button onclick="myFunction1()" id="alert">simpleAlert</button> <p>Click the button to display a confirm box.</p> <button onclick="myFunction2()" id="confirm">confirmBox</button> <p id="demo1"></p> <p>Click the button to demonstrate the prompt box.</p> <button onclick="myFunction3()" id="prompt">prompt</button> <p id="demo2"></p> <script> function myFunction1() { alert("I am a simple alert box!"); } function myFunction2() { var x; if (confirm("Press a button!") == true) { x = "You pressed OK!"; } else { x = "You pressed Cancel!"; } document.getElementById("demo1").innerHTML = x; } function myFunction3() { var person = prompt("Please enter your name", "PTR Nayan"); if (person != null) { document.getElementById("demo2").innerHTML = "Hello " + person + "! How are you?"; } } </script> </body> </html>
Following application clicks on all alert boxes.
import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class App { public static void main(String[] args) throws InterruptedException { WebDriver driver = new FirefoxDriver(); driver.get("http://localhost:8080/application/"); WebElement alertEle = driver.findElement(By.id("alert")); WebElement confirmEle = driver.findElement(By.id("confirm")); WebElement promptEle = driver.findElement(By.id("prompt")); alertEle.click(); Alert alert = driver.switchTo().alert(); System.out.println(alert.getText()); alert.accept(); confirmEle.click(); alert = driver.switchTo().alert(); System.out.println(alert.getText()); alert.accept(); System.out.println(driver.findElement(By.id("demo1")).getText()); promptEle.click(); alert = driver.switchTo().alert(); alert.sendKeys("Hari Krishna"); alert.accept(); System.out.println(driver.findElement(By.id("demo2")).getText()); Thread.sleep(9000); driver.quit(); } }
Output
I am a simple alert box! Press a button! You pressed OK! Hello Hari Krishna! How are you?
No comments:
Post a Comment