Check if a WebElement is stale without handling an exception

Webdriver itself uses the try/catch-construction to check for staleness as well.

from org.openqa.selenium.support.ui.ExpectedConditions.java:

  public static ExpectedCondition<Boolean> stalenessOf(final WebElement element) {
    return new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver ignored) {
        try {
          // Calling any method forces a staleness check
          element.isEnabled();
          return false;
        } catch (StaleElementReferenceException expected) {
          return true;
        }
      }

      @Override
      public String toString() {
        return String.format("element (%s) to become stale", element);
      }
    };
}

The isEnabled() check is better than using a click action – clicking an element might cause unwanted side effects, and you just want to check the element’s state.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)