I'm currently checking to see if a WebElement is stale by doing the following:
public static boolean isStale(WebElement element) { try { element.click(); return false; } catch (StaleElementReferenceException sere) { return true; } }
This is the same as the solution offered to this question:
Check for a stale element using selenium 2?
However, this seems rather messy to me. Is there a cleaner way that I can check if an element is stale, without having to throw and catch an exception?
(Also, as a side, if I have to stick with throwing and catching an exception, is there something better to do than clicking/sending keys/hovering to throw said exception? I might have a WebElement that I don't want to do any of these actions on, as it may inadvertently affect something else.)
A stale element reference exception is thrown in one of two cases, the first being more common than the second: The element has been deleted entirely. The element is no longer attached to the DOM.
The stale element reference error is a WebDriver error that occurs because the referenced web element is no longer attached to the DOM. Every DOM element is represented in WebDriver by a unique identifying reference, known as a web element.
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.
I know this already has an accepted answer and I don't know the bigger context of how you use the staleness check but maybe this will help you or others. You can have ExpectedConditions.stalenessOf(WebElement)
do the work for you. For example,
WebElement pageElement = driver.findElement(By.id("someId")); WebDriverWait wait = new WebDriverWait(webDriver, 10); // do something that changes state of pageElement wait.until(ExpectedConditions.stalenessOf(pageElement));
In this case, you don't have to do pageElement.click()
, etc. to trigger the check.
From the docs, .stalenessOf()
waits until an element is no longer attached to the DOM.
References: ExpectedConditions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With