Implement a global listener for Selenium tests

Viewed 161

I use this code to click on a series of dialog windows with unique button ID. It was working fine till now because the order was strict:

clickConfirmWindow(driver, SURVEY_EXIT_BUTTON_ID_LOCATOR, "Survey exit window");

... and many mode windows with unique ID with random order

protected void clickConfirmWindow(WebDriver driver, String elementId, String name) {
        // Check if warning window is displayed using button ID
        System.out.println("Searching " + name + " using " + elementId);
        if (isClickable(driver, elementId, 1)) {
            System.out.println("Found " + name + " using " + elementId);
            driver.findElement(By.id(elementId)).click();
        }
    }

protected void clickConfirmWindow(WebDriver driver, String elementId, String name) {
        // Check if warning window is displayed using button ID
        System.out.println("Searching " + name + " using " + elementId);
        if (isClickable(driver, elementId, 1)) {
            System.out.println("Found " + name + " using " + elementId);
            driver.findElement(By.id(elementId)).click();
        }
    }

private Boolean isClickable(WebDriver driver, String elementId, int timeOut) {
        try {
            new WebDriverWait(driver, timeOut).until(ExpectedConditions.visibilityOfElementLocated(By.id(elementId)));
            return true;
        } catch (TimeoutException e) {
            e.printStackTrace();
            return false;
        }
    }

But now the order of the windows is random. Is it possible to implement some kind of global listener which listens for web element ID thru out the entire application and clicks it if it's present?

2 Answers

not sure about your specific situation but in vba I would write an if statement to see if it was true,

If driver.findelementsbyid("your Id").count > 0 then driver.findelementbyid("your Id").click Else End if

Searching if the element exists should help you

WebElement elementName = driver.findElement(By.id("idElement")); 

if(elementName != null){
   //Loaded Element 
}
Related