Generally JavaScript popups are generated by web application and hence they can be easily controlled by the browser.
// Get a handle to the open alert, prompt or confirmation
Alert alert = driver.switchTo().alert();
Alert is an interface. There below are the methods that are used
//Will Click on OK button.
alert.accept();
// Will click on Cancel button.
alert.dismiss()
//will get the text which is present on th Alert.
alert.getText();
//Will pass the text to the prompt popup
alert.sendkeys();
//Is used to Authenticate by passing the credentials
alert.authenticateUsing(Credentials credentials)
// Get a handle to the open alert, prompt or confirmation
Alert alert = driver.switchTo().alert();
Alert is an interface. There below are the methods that are used
//Will Click on OK button.
alert.accept();
// Will click on Cancel button.
alert.dismiss()
//will get the text which is present on th Alert.
alert.getText();
//Will pass the text to the prompt popup
alert.sendkeys();
//Is used to Authenticate by passing the credentials
alert.authenticateUsing(Credentials credentials)
Sample Program to handle alerts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test.qaearth; | |
import org.openqa.selenium.Alert; | |
import org.openqa.selenium.By; | |
import org.openqa.selenium.firefox.FirefoxDriver; | |
public class PopupsHandling { | |
public static void main(String a[]) throws InterruptedException { | |
System.setProperty("webdriver.gecko.driver", "Drivers/geckodriver.exe"); | |
FirefoxDriver driver = new FirefoxDriver(); | |
driver.manage().window().maximize(); | |
driver.navigate().to("https://qaearth.blogspot.in/p/testing-examples.html"); | |
driver.findElement(By.cssSelector("#alert")).click(); | |
Thread.sleep(2000); | |
Alert alert = driver.switchTo().alert(); | |
System.out.println(alert.getText()); | |
alert.sendKeys("Krishna"); | |
alert.accept(); | |
// Dismiss | |
driver.findElement(By.cssSelector("#alert")).click(); | |
Thread.sleep(2000); | |
Alert alert = driver.switchTo().alert() | |
alert.dismiss(); | |
} | |
} |