Handling Alerts and pop-ups in Selenium | Alerts & pop-up





Handling alerts and pop-ups in Selenium can be done using the Alert interface. The Alert interface provides methods to interact with alerts and pop-ups.


Here are some examples of how to handle alerts and pop-ups in Selenium:


1.To handle a simple alert:


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

In this example, the switchTo().alert() method is used to switch the focus of the WebDriver to the alert. The accept() method is then used to click the "OK" button on the alert.



2.To handle a confirm alert:

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


In this example, the switchTo().alert() method is used to switch the focus of the WebDriver to the confirm alert. The dismiss() method is then used to click the "Cancel" button on the confirm alert.



3.To handle a prompt alert:

Alert alert = driver.switchTo().alert();
alert.sendKeys("my input");
alert.accept();


In this example, the `switchTo().alert() method is used to switch the focus of the WebDriver to the prompt alert. ThesendKeys("my input")method is then used to enter a value in the prompt input field. Finally, theaccept()` method is used to click the "OK" button on the prompt alert.



It's also worth noting that you can also use the getText() method to get the text of the alert message and authenticateUsing() method to handle basic auth popups.


Here is an example of how to use getText() method:


Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("Alert text: " + alertText);
alert.accept();



Here is an example of how to use authenticateUsing() method:


Alert alert = driver.switchTo().alert();
alert.authenticateUsing(new UserAndPassword("username","password"));



It's important to note that when working with alerts and pop-ups, it's important to switch the focus of the WebDriver to the alert before interacting with it. Once you are done interacting with the alert, you should switch the focus back to the main window using driver.switchTo().defaultContent() method.


Also, it's important to use try-catch block to handle the NoAlertPresentException that could be thrown if an alert is not present or if the alert is not visible to the user.

Post a Comment

Post a Comment (0)

Previous Post Next Post