What is a stale element and how to fix it

What is a stale element and how to fix it

December 3, 2015

CoreValue code experts are big fans of sharing their experience with technologies and sophisticated solutions.

If you are reading this you must have encountered  stale element.

As you may already know a ‘stale element’ means == an old, outdated element…

An element can become outdated if a page is changed somewhere in between element declaration and actual use of element. (changes are usually caused by JavaScript, Ajax,JQuery etc.)

A common scenario looks like this:

Element declaration =>Actions that cause changes(JS,Ajax etc.)=>use of element => Stale Element exception.

The simple example is:

1
2
3
4
5
6
/*
WebElement element = driver.findElement(By.id(“search button”)); //we declare the element
element.click()              // this action triggers some updates (page/table refresh etc.)
element.click()                                        // this line would give stale element exception
*/

There are two possible ways to get Stale element exception:

  • The element has been replaced entirely.

In first case: JS library or Ajax replaced an element with another one with the same ID or attributes. This element may look identical but it is different; the driver does not know if the replaced element is actually what’s expected and will give a Stale Element exception.

A common technique in a web app is to prepare DIVs for each tab, but only attach one at a time. Your code might have a reference to an element that is no longer attached to the DOM (that is, that has an ancestor which is “document.documentElement”).

How to fight and avoid Stale Elements.

There are many ways of dealing with Stale Element Exception on the web. Here I gathered the ones that I personally find most useful.

  • A good practice is to use @FindBy annotation because of Lazy Initialization This way elements will be initialized right before actual usage.

Example: @FindBy(xpath=”someXpath” ) public WebElement someElement;

  • Use wait methods for JavaScript, Ajax, Jquery etc. This will solve the “Race condition” that causes this exception to occur.

Examples:

This method waits for all jQuery to finish.

1
2
3
4
5
6
7
8
public void waitForAjax() {
new WebDriverWait(driver, waitTimeout).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
JavascriptExecutor js = (JavascriptExecutor) d;
return (Boolean) js.executeScript(“return jQuery.active == 0”);
}
});
}

This method waits for page to be loaded.

1
2
3
4
5
6
7
8
9
10
11

public void waitForPageToLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript(“return                            document.readyState”).equals(“complete”);
}
};
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}

  • More common practice is to use try catch in a loop.
1
2
3
4
5
6
7
8
9
10
11
12
13

while(attempts < 3) {
try {
driver.findElement(by).click();
result = true;
break;
} catch(StaleElementException e) {

System.out.println(“Caught Stale Element here”);
}
attempts++;
}
return result;
}

NOTE: This approach is not very flexible and should only be used if ‘stale element’ cannot be prevented by other means. Also we should always put a system.out message into catch block, this will spare you few hours if you get an error anyway.

  • Working with lists solution.

If you have a piece of code similar to this one:

1
2
3
4

List<WebElement> elements = driver.findElements(By.xPath(“someXpath”));
for(WebElement element : elements) {
// your code should be here
}

Try changing it to a format below. Doing so your element will be declared directly before actual usage.

1
2
3
4
5
6

int listSize = driver.findElements(By.xPath(“someXpath”)).size();
for(int i = 1; i <= listSize; i++) {
String locator = someXpath+’[’+i+’]’;
WebElement element = driver.findElement(By.xPath(locator));
// your code should be here
}

Hope this information was helpful. Try preventing the problem so you won’t have to fix it later!

Tags



Share


Recent Articles

Get 100% Code Coverage for Salesforce Custom Metadata Based Decisions

January 18, 2018 | Bohdan Dovhan

How to obtain a full coverage for code which uses Custom Metadata for strategy-like decision implementation? Introduction Many applications use configuration data. Configuration data might be relevant to the entire organization, or a subset of user, or even different for each user. For the purposes of this article, we will focus only on global configuration […]

Logging of Exceptions in Salesforce

January 11, 2018 | Mykola Senyk

Unpredicted behaviour in a custom code. Can we eliminate it? The ability to customize your Salesforce org code is not just a “nice to have.”  It greatly increases the capability and flexibility of Salesforce. However, custom code can also be tricky to use. It would be great if we could detect unpredicted behavior in our […]

© Copyright - CoreValue 2018
Salesforce, Sales Cloud, and others are trademarks of salesforce.com, inc., and are used here with permission.
Used with permission from Microsoft.