Friday, May 22, 2020

Alert & Popup Window Handling in Selenium WebDriver

Alert is a small message box which displays on-screen notification to give the user some kind of information or ask for permission to perform certain kind of operation.
Types of Alerts in Selenium
Mainly we are dealing with two types of alerts that are:
  • Windows-based alert pop-ups
  • Web-based alert pop-ups
As we know that by using the Selenium WebDriver its is not possible to test window bases applications, that’s why we are using some third-party tools to handle the window-based pop-ups.
1. Simple Alert: It displays some information or warning on the screen.
2. Prompt Alert: This Prompt Alert asks some input from the user and selenium webdriver can enter the text using sendkeys(" INPUT").
3. Confirmation Alert: This confirmation alert asks permission to do some type of operation.
Methods of Handling Alerts:
1) void dismiss() // To click on the 'Cancel' button of the alert.
driver.switchTo().alert().dismiss();

2) void accept() // To click on the 'OK' button of the alert.
driver.switchTo().alert().accept();

3) String getText() // To capture the alert message.
driver.switchTo().alert().getText();
4) void sendKeys(String stringToSend) // To send some data to alert box.
driver.switchTo().alert().sendKeys("Text");


package com.automation.eng.AutomationProject;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import io.github.bonigarcia.wdm.WebDriverManager;

public class AlertHandling {

public WebDriver driver;

@Test
public void mouseHover() throws InterruptedException{

//setup the firefoxdriver using WebdriverManager
WebDriverManager.firefoxdriver().setup();

//Create driver object for Chrome
driver = new FirefoxDriver();

String url = "https://www.w3schools.com/js/tryit.asp?filename=tryjs_alert ";
//To maximize the browser
driver.manage().window().maximize();
//To delete all cookies
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//To invoke URL
driver.get(url);

//Switching to frame on same web page
driver.switchTo().frame("iframeResult");

// Locating and clicking on "Try it" button
driver.findElement(By.tagName("button")).click();

//Switching to Alert on same web page
Alert alert = driver.switchTo().alert();

// Fetching message on Alert box in a String
String messageOnAlert = alert.getText();

//displaying the message on Alert message
System.out.println("Message on Alert : "+ messageOnAlert);

// Explicit wait of 4 seconds so that you can see Alert for sometime
Thread.sleep(4000);

//Accepting an alert
alert.accept();

//Switching to parent page
driver.switchTo().defaultContent();
driver.close();
}
}
/*
* Message on Alert : I am an alert box!
*/
/

No comments:

Post a Comment