☰ See All Chapters |
Handling JavaScript alert in Selenium Webdriver
WebDriver provides an “Alert” class for handling alerts. When an alert is displayed, we have to switch to alert popup to access it. To access the alert box displayed on the screen as an instance of the “Alert” class, the “driver.switchTo().alert()” method is used as follows:
driver.findElement(By.id("alert")).click();
Alert alert = driver.switchTo().alert();
“NoAlertPresentException” exception will be thrown if there is no alert present and “driver.switchTo().alert()” is called.
“getText()” method of the “Alert” class returns the text displayed on alert popup.
String textOnAlert = alert.getText();
To click on “OK” button on alert popup “accept()” method is called.
alert.accept();
To dismiss or cancel alert popup “dismiss()” method is called.
alert.dismiss();
The below example explains how to automate javascript alert pop up.
import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.junit.Assert;
public class Example {
public static void main(String[] args) {
// configure chromedriver System.setProperty("webdriver.chrome.driver", "F:\\My_Programs\\Selenium\\ChromeDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// Launch website driver.get("https://www.tools4testing.com/contents/selenium/testpages/handling-javascript-pop-ups-testpage");
driver.findElement(By.id("alert")).click(); Alert alert = driver.switchTo().alert(); String textOnAlert = alert.getText(); Assert.assertEquals(textOnAlert, "www.tools4testing.com"); alert.accept();
//wait some time before closing try { Thread.sleep(7000); } catch (InterruptedException ie) { } System.out.println("-------------------------------DONE----------------------------------");
//close the driver driver.quit();
} } |
You can write the script and test these using our Test Page
All Chapters