How to refresh a stale WebElement if the locator isn't known prior to runtime?

33 views Asked by At

Background: This project is using Page Object Models to define WebElements that are used as base references to find children that may or many not exist during runtime.

@FindBy(xpath = "//app-header//div/button")
protected List<WebElement> globalHeaderButtons;

We then use methods to find and interact with specific child elements as needed. These elements may or may not exist during runtime depending on the state of the webpage and data in the DB.

public boolean clickGlobalHeaderButton(String button) {
   for(WebElement element : globalHeaderButtons) {
      element = common.waitElement(element);
      if(element.getText().contains(button) {
         return element.click();
      }
   }
   return false;
}

Another file:

// This is initialized in the constructor of the class
private WebDriverWait wait = new WebDriver(this.driver, Duration.ofSeconds(8));

public WebElement waitElement(WebElement element) {
   return wait.until(ExpectedConditions.visibilityOf(element));
}

Sometimes when interacting with the elements we are sent to new pages with new elements with the same locators. In this example an error I might encounter an error in the wait function stating that the element is stale. Even after trying to use a wait function it refuses to see the element even after it is loaded. I think it has to do with Java being call by value and not call by reference. In order to resolve this we have been using implicit waits prior to calling these functions. How can I create a wait function that takes a WebElement as input and returns a non-stale element with the same locators if one exists?

I have tried using try-catch blocks in a loop to check if element is displayed in waitElement() function, this results in an infinite loop. I need a wait function that can return a non stale element after waiting a given duration when passed an element that could be stale without knowing the locators beforehand.

0

There are 0 answers