Handle Alert in WebDriver selenium

Selenium WebDriver has Alert Class to handle the popups.

When the Alert is displayed during runtime by the application,We can cancel the popup or else click on the OK button on the alert box. 

We can also get the message on the alert box.

Before using the below methods, create object for Alert class like below

Alert alert = driver.switchTo().alert();

Alert class provides below methods
  •     accept()  ---click on ok button on alert
  •     dismiss()  ----cancel the alert message
  •     getText()  ----get the text displayed on the alert
  •     sendkeys(key)--- to perform keyboard inputs on the alert  like press enter / tab / any function keys / type any chars..etc
     Ex: sendkeys(keys.RETURN)--- will press enter key

The below code will handle the alert displayed in Spicejet .com while booking domestic flight

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Reporter;
import org.testng.annotations.Test;

public class webd_spicejet
{
   
    public void fn_booking(String br) throws Exception
    {    
     FireFoxDriver fd=new FirefoxDriver();
     fd.get("http://www.spicejet.com");
     Thread.sleep(10000);
     fd.findElement(By.id("oneWayRadio")).click();
     new Select(fd.findElement(By.id("from1Select"))).selectByVisibleText("Chennai");
     new Select(fd.findElement(By.id("to1Select"))).selectByVisibleText("Delhi");
     fd.findElement(By.id("departDate1text")).click();
     Thread.sleep(2000);
     fd.findElement(By.linkText("26")).click();
     fd.findElement(By.id("submitBtn")).click();
     Alert a=fd.switchTo().alert();      /////////swith to alert
     String s=a.getText();                    ///////////read text displayed in the alert
     a.accept();
     Reporter.log(s);
     fd.close();
    }   
}

Comments

Post a Comment