Home >>Selenium Tutorial >Selenium WebDriver - Handling Alerts

Selenium WebDriver - Handling Alerts

Selenium WebDriver - Handling Alerts

You'll learn how to handle alerts in the Selenium WebDriver section here.

Selenium WebDriver offers three ways of acknowledging and refusing the Alert, based on the type of alert.

1. void dismiss()

This method is used to click on the 'Cancel' button of the alert.

Syntax:

driver.switchTo().alert().dismiss();

2. void accept()

This method is used to click on the 'Ok' button of the alert.

Syntax:

driver.switchTo().alert().accept();  

3. String getText()

This method is used to capture the alert message.

Syntax:

driver.switchTo().alert().getText();

next →← prev

Selenium WebDriver- Handling Alerts

In this section, you will learn how to handle alerts in Selenium WebDriver.

Selenium WebDriver provides three methods to accept and reject the Alert depending on the Alert types.

1. void dismiss()

This method is used to click on the 'Cancel' button of the alert.

Syntax:

driver.switchTo().alert().dismiss();  

2. void accept()

This method is used to click on the 'Ok' button of the alert.

Syntax:

driver.switchTo().alert().accept(); 

3. String getText()

This method is used to capture the alert message.

Syntax:

driver.switchTo().alert().getText();

4. void sendKeys(String stringToSend)

This method is used to send some data to the alert box.

Syntax:

driver.switchTo().alert().sendKeys("Text");  

Let us find a test case, in which the following situations would be automated:

  • Enable Browser for Firefox
  • Open URL: https://www.testandquiz.com/selenium/testing.html
  • Click on the "Generate Alert box" button
  • Click on the "Generate Confirm box" button
  • Close the browser

To give you a better understanding of how to treat alerts in WebDriver, we will build our test case step by stage.

Step 1. Activate Eclipse IDE and open the current "Demo_Test" test set, which we built in earlier tutorial sessions.

Step 2. Right click on the "src" folder and create a new Class File from New > Class.

Give your Class name as "alert_test" and click on "Finish" button.

Step 3. Let's get to the world of coding.

To trigger the Firefox browser, Gecko driver must be downloaded and the system properties configured for the Gecko driver. We have discussed this in earlier tutorial sessions already. To know how to access and install system properties for Firefox app, link to "Running check on Firefox Browser."

Here's the sample code for Gecko driver setting system property:

// System Property for Gecko Driver   
stem.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );  

We have to initialize Gecko Driver after that using the Required Capabilities Level.

Here is the sample code for initializing gecko driver utilizing class DesiredCapabilities.

// Initialize Gecko Driver using Desired Capabilities Class  
DesiredCapabilities capabilities = DesiredCapabilities.firefox();  
capabilities.setCapability("marionette",true);  
ebDriver driver= new FirefoxDriver(capabilities);  

Combining both of the above code blocks, we will get the code snippet to launch Firefox browser.

// System Property for Gecko Driver   
System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );  
// Initialize Gecko Driver using Desired Capabilities Class  
DesiredCapabilities capabilities = DesiredCapabilities.firefox();  
capabilities.setCapability("marionette",true);  
WebDriver driver= new FirefoxDriver(capabilities);

After that we have to compose the application that will simplify our second test scenario (navigate to the URL of your selection)

Below is the sample code for navigating to the URL you want to use:

// Launch Website  
driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");   

The complete code till now will look something like this:

import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.firefox.FirefoxDriver;  
import org.openqa.selenium.remote.DesiredCapabilities;  
  
public class alert_test {  
  
    public static void main(String[] args) {  
          
    // System Property for Gecko Driver   
        System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );  
              
    // Initialize Gecko Driver using Desired Capabilities Class  
DesiredCapabilities capabilities = DesiredCapabilities.firefox();  
            capabilities.setCapability("marionette",true);  
            WebDriver driver= new FirefoxDriver(capabilities);  
          
  
      // Launch Website  
driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");   
      
    }  
  
}  

Stage 4. Now, to conduct alert handling activity, we must seek to find the "Generate Alert Box" and "Generate Confirm Box." As we know it requires inspection of their HTML codes to find an item.

To find the drop-down menu on the sample web page, follow the steps provided below.

  • Open URL: https://www.testandquiz.com/selenium/testing.html
  • Right click on the "Generate Alert Box" button and select Inspect Element.
  • This will open a window which contains all the different codes involved in the "Generate Alert Box" button development.

Step 5. To automate our third and fourth test scenarios, we need to write the code that clicks and accepts the Generate Alert box, and click the Generate Confirm box to accept.

The code snippet provided below is for automating our third and fourth test scenarios.

//Handling alert boxes  
//Click on generate alert button  
driver.findElement(By.linkText("Generate Alert Box")).click();  
          
//Using Alert class to first switch to or focus to the alert box  
Alert alert = driver.switchTo().alert();  
          
//Using accept() method to accep the alert box  
alert.accept();  
          
//Handling confirm box  
//Click on Generate Confirm Box  
driver.findElement(By.linkText("Generate Confirm Box")).click();  
                 
Alert confirmBox = driver.switchTo().alert();  
          
//Using dismiss() command to dismiss the confirm box  
//Similarly accept can be used to accept the confirm box  
confirmBox.dismiss();  

Thus, our final test script will look something like this:

import org.openqa.selenium.By;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.firefox.FirefoxDriver;  
import org.openqa.selenium.remote.DesiredCapabilities;  
import org.openqa.selenium.Alert;  
public class alert_test {  
  
    public static void main(String[] args) {  
          
        // System Property for Gecko Driver   
 System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" ;  
              
        // Initialize Gecko Driver using Desired Capabilities Class  
            DesiredCapabilities capabilities = DesiredCapabilities.firefox();  
            capabilities.setCapability("marionette",true);  
            WebDriver driver= new FirefoxDriver(capabilities);  
          
  
        // Launch Website  
        driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");   
  
        //Handling alert boxes  
        //Click on generate alert button  
        driver.findElement(By.linkText("Generate Alert Box")).click();  
          
        //Using Alert class to first switch to or focus to the alert box  
        Alert alert = (Alert) driver.switchTo().alert();  
          
        //Using accept() method to accept the alert box  
        alert.accept();  
          
        //Handling confirm box  
        //Click on Generate Confirm Box  
        driver.findElement(By.linkText("Generate Confirm Box")).click();  
          
          
        Alert confirmBox = (Alert) driver.switchTo().alert();  
          
        //Using dismiss() command to dismiss the confirm box  
        //Similarly accept can be used to accept the confirm box  
        ((Alert) confirmBox).dismiss();  
    }  
}