×
☰ See All Chapters

Handling JavaScript confirm in Selenium WebDriver

WebDriver provides an “Alert” class for handling confirm popup. “Alert” class handles all alert, confirm, and prompt javascript popups. When a confirm popup is displayed, we have to switch to confirm popup to access it. To access the confirm 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("confirm")).click();               

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

 “NoAlertPresentException” exception will be thrown if there is no confirm present and “driver.switchTo().alert()” is called.

To click on “OK” button on confirm popup “accept()” method is called.

alert.accept();

To dismiss or cancel confirm 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("confirm")).click();               

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

                confirmAlert.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

handling-javascript-confirm-in-selenium-webdriver-0
 

All Chapters
Author