Software Development and QA Tips By QASource Experts

How to Handle Alert Box in Selenium?

Written by Ross Jackman | Jun 5, 2023 4:00:00 PM

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();