Selenium WebDriver -Handling JavaScript alerts


Handling JavaScript alerts of a web page using Selenium Webdriver is illustrated with an example below.
On clicking on link/button in a webpage,we can shift the focus to java script alert/prompt by using
driver.switchTo().alert() .


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class javascriptalerts
{

  @Test
  public void auth()
  {
 WebDriver driver=new FirefoxDriver();

 driver.get("http://the-internet.herokuapp.com/javascript_alerts");

 //1.click on javascript alert

 
  driver.findElement(By.xpath("html/body/div[2]/div/div/ul/li[1]/button")).click();

 System.out.println(driver.switchTo().alert().getText());//To fetch the text in the alert

 driver.switchTo().alert().accept();//clicking on OK button can be done using accept method.*/

 //2.click on javascript confirm box

 driver.findElement(By.xpath("html/body/div[2]/div/div/ul/li[2]/button")).click();

 System.out.println(driver.switchTo().alert().getText());

 driver.switchTo().alert().dismiss();//clicking on Cancel button can be done using dismiss method.*/

 //3.click on javascript prompt

 driver.findElement(By.xpath("html/body/div[2]/div/div/ul/li[3]/button")).click();

 System.out.println(driver.switchTo().alert().getText());

 driver.switchTo().alert().sendKeys("test");

 driver.switchTo().alert().dismiss();//clicking on Cancel button.*/

 }
}

Comments

Post a Comment

Popular posts from this blog

Cypress Cheat Sheet

Selenium WebDriver-Working with Listbox and Multi-Select Listbox