Reading list Switch to dark mode

    Alerts/Popup Handling in Selenium WebDriver

    Updated 17 January 2020

    What is alert?

    Alert is a small message box that appears on your screen to give some kind of information or asking for permission to perform certain operation. Alerts are blocking in nature they will not allow you to perform any action on the underlying webpage if present. Alert is basically used to display a warning message. 

    How to handle alerts in Selenium

    Selenium provides an interface called “Alert”.  It is available in the org.openqa.selenium.Alert package. Alert interface provide us four methods to deal with the Alert-

    • accept() To accept the alert
    • dismiss() To dismiss the alert
    • getText() To get the text of the alert
    • sendKeys() To write some text to the alert

    Types Of Alerts in Selenium

    There are three types of Alerts in Selenium

    • Simple Alert
    • Prompt Alert
    • Confirmation Alert

    Simple Alert

    Simple Alert are just used to display any kind of information. It consist of Ok button.

    Note- To handle any pop-up we need to switch from main window to that popup using driver.switchTo().alert().

    Start your headless eCommerce
    Find out More

    In below code we will learn how to read information from alert –

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


    Prompt Alert

    Prompt alert is generally used when some input is required from the user. This alert come with text box. sendkeys() method is used to pass information in Prompt alert text box.

     Alert promptAlert  = driver.switchTo().alert();
     String alertText = promptAlert .getText();
     System.out.println("Alert text is " + alertText);
     //Send some text to the alert
     promptAlert .sendKeys("Accepting the alert");
     promptAlert .accept();

    Confirmation Alert

    The confirmation alert ask for permission to perform or continue to perform certain type of operation. In order to accept the alert, you can use the Alert.accept()and to dismiss, use Alert.dismiss()

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

    Thanks for reading this Blog.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*

    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home