How to Handle Alert Box in Selenium?

Author: Ross Jackman
Ross Jackman | June 5, 2023

How to Handle Alert Box in Selenium?

In any advanced automation framework, having reusable libraries to handle Alerts is a great advantage. There are multiple types of alerts or pop-ups that can be handled accordingly.

Web-based Alerts: These are small message boxes or windows which can be handled by Selenium WebDriver. These Web Alerts can be of different types and can be handled by implementing the corresponding default methods that Selenium WebDriver provides.

  1. OK Button: This requires clicking on the 'OK' button on the prompt. This can be handled by using the accept method and syntax is:

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

  2. Cancel Button: Click on the 'Cancel' button on a prompt is possible by using the dismiss method and the syntax is:

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

  3. Inputting Data: When a prompt demands data to input, the following method is used:

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

  4. Fetching Data: When data needs to be fetched from the prompt, then following method is used:

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

Disclaimer

This publication is for informational purposes only, and nothing contained in it should be considered legal advice. We expressly disclaim any warranty or responsibility for damages arising out of this information and encourage you to consult with legal counsel regarding your specific needs. We do not undertake any duty to update previously posted materials.

Post a Comment