Keyword-Driven Alert Handling in Selenium

Alerts and other pop ups cause your well-crafted Selenium tests to grind to a stop unless you handle them properly. The reason for this is that control moves to the alert instead of continuing with the open browser.

In most cases, you just need just need to automate accepting or rejecting the alert buttons which is relatively straightforward.

If you are using a keyword-driven framework, you need to do the following to handle alerts in Selenium.

  1. Find the ID of the button which opens the alert window. You can do this easily with Firebug in Firefox.
  2. Pass this ID. We have an Excel-based framework that we use where we can specify keywords and objects. The ID of the button would be the object in our framework.
  3. Invoke acceptAlertButtonByID or dismissAlertButtonByID keywords by specifying the exact name of the keyword in Excel.
The following Java code contains the keywords for accepting or dismissing buttons.
[code lang="java"]//To click the button by which an alert is generated and then accept the alert using id
    public  String acceptAlertButtonByID(String object,String data){
           APP_LOGS.debug("Clicking on button and acccepting the alert");
           try{
               driver.findElement(By.id(object)).click();
               Alert alert = driver.switchTo().alert();
              alert.accept();
               }catch(Exception e){
                    return Constants.KEYWORD_FAIL+" Not able to accept alert";
              }
            return Constants.KEYWORD_PASS;
    }

//To click the button by which an alert is generated and then dismiss the alert using id
    public  String dismissAlertButtonByID(String object,String data){
           APP_LOGS.debug("Clicking on button and dismissing the alert");
           try{
               driver.findElement(By.id(object)).click();
               Alert alert = driver.switchTo().alert();
               alert.dismiss();
               }catch(Exception e){
                    return Constants.KEYWORD_FAIL+" Not able to dismiss alert";
              }
            return Constants.KEYWORD_PASS;
    }[/code]

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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