Your ultimate guide

Handling Alerts with Selenium


Handling Alerts:
    In Selenium, alerts are popup dialog boxes that appear on a web page to provide information, take user input or request confirmation of specific actions. Selenium provides methods to interact with these alerts, allowing you to automate actions such as accepting, dismissing, or entering text into them.
Here's how you can work with alerts in Selenium:

switchTo().alert():
    To interact with an alert, you first need to switch the WebDirver's focus to it using the 'switchTo().alert()' method, and then we need to perform the action.
  1. Accept an Alert: Click OK an alert and close it
    • driver.switchTo().alert().accept();
  2. Dismiss an Alert: Click Cancel or the equivalent of an alert and close it.
    • driver.switchTo().alert().dismiss();
  3. Enter Text into a Prompt Alert: If the alert is prompt that requires you to enter text, you can use the 'sendKeys()' method to provide input.
    • driver.switchTo().alert().sendKeys("Your Input text");
  4. Get Text from an Alert: To retrieve the text displayed in an alert.
    • driver.switchTo().alert().getText();

Example Program:
  1. import org.openqa.selenium.By;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.WebElement;
  4. import org.openqa.selenium.chrome.ChromeDriver;

  5. public class Alert2 {
  6.   public static void main(String[] args) throws InterruptedException {
  7.     WebDriver driver = new ChromeDriver();
  8.     driver.get("https://testingcolleges.blogspot.com/2023/08/alerts-demo-pages.html");
  9.     WebElement confirmbox = driver.findElement(By.id("confirmbox"));
  10.     confirmbox.click();
  11.     driver.switchTo().alert().accept();
  12.     confirmbox.click();
  13.     driver.switchTo().alert().dismiss();
  14.     WebElement promptbox = driver.findElement(By.id("promptbox"));
  15.     promptbox.click();
  16.     driver.switchTo().alert().sendKeys("Happy");
  17.     driver.switchTo().alert().accept();
  18.   }
  19. }



 
switchTo().activeElement()
    To automate active element current webpage.
For example, when we open some websites, by default one element will be selected to select such type of active element we will use this method.

Example: driver.switchTo().activeElement().sendKeys(“Hello”);





No comments:

Post a Comment