Menu Close
    Searching for an experienced eCommerce & Marketplace Development Company ?

    Alerts/Popup Handling in Selenium WebDriver

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

    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); 
    
    simpleAlert.accept();
    

    Screenshot1-3

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

    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);
     confirmationAlert.dismiss();
    Screenshot3-2

    Thanks for reading this Blog.

    . . .
    Discuss on Helpdesk

    Leave a Comment

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


    Be the first to comment.

    Back to Top