What is the best way to handle a Javascript popup using Selenium Webdriver?

We can handle a JavaScript pop-up using Selenium webdriver with the help of the Alert interface. The alerts are pop-ups that shift the focus from the main webpage to the alert text appearing on the page.

By default, the webdriver has focus on the main page, to access the alert we have to explicitly switch the driver focus from the main page to the alert box. The alerts can be of two types – web based and window based. JavaScript pop-ups are the web based alerts.

The switchTo().alert() method is used to switch the driver focus to the alert. Once the driver focus is shifted, we can obtain the text of the pop-up with the help of the method switchTo().alert().getText(). Finally we shall use the switchTo().alert().accept() method to accept the alert and switchTo().alert().dismiss() method to dismiss it.

To input text inside a confirmation alert, the method switchTo().alert().sendKeys() is used. The text to be entered is passed as a parameter to this method. Also, we have to add import org.openqa.selenium.Alert statement to work with alerts.


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
public class JavaScriptAlert{
   public static void main(String[] args) {
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      // identify element
      WebElement a =driver.findElement(By.xpath("//button[text()='Click for JS Confirm']"));
      //switch alert
      Alert al = driver.switchTo().alert();
      //obtain text
      String st = al.getText();
      System.out.println("Text is: " + st);
      //alert dismiss
      //alert accept


Updated on: 06-Apr-2021


Kickstart Your Career

Get certified by completing the course

Get Started