Handling modal JavaScript alerts

We have created a sample HTML page with a textbox and button. When the Display Alert button is clicked, the modal alert is displayed with OK and Cancel buttons. At this point, the textbox on the main page cannot be accessed. When the OK or Cancel buttons are clicked, an appropriate message is displayed on the main page. 

The following code will click on the Display Alert button and later will click once on the Ok button of the modal alert, and the next time will click on the Cancel button:

 WebDriver driver = new ChromeDriver();
driver.navigate().to(
"C:\modalalert.html");
driver.findElement(By.id("dispalert")).click();
Alert alert = driver.switchTo().alert();
alert.accept();
driver.findElement(By.id("text1")).sendKeys("Ok clicked");
driver.findElement(By.id("dispalert")).click();
driver.switchTo().alert();
alert.dismiss();
 driver.findElement(By.id("text1")).clear();
driver.findElement(By.id("text1")).sendKeys("Cancel clicked");

In the preceding code, we find two new methods invoked on the Alert object, which are accept() and dismiss():

  • accept(): Clicks on the Ok button of the alert
  • dismiss()Clicks on the Cancel button of the alert

These methods will throw a NoSuchAlertError if the alert does not exist at that time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset