How to Handle Stale Element Reference Exception in java

Code Green - Feb 20 '21 - - Dev Community

Android app for all Automation Testing Interview Questions from PlayStore
⬇️Download Here👈

Background:
What is StaleElementReferenceException? Stale means old, decayed, no longer fresh. Stale Element means an old element or no longer available element. Assume there is an element that is found on a web page referenced as a WebElement in WebDriver. If the DOM changes then the WebElement goes stale. If we try to interact with an element which is staled then the StaleElementReferenceException is thrown.

Selenium keeps a track of all elements in form of a Reference as and when findElement/findElements is used. And while reusing the element, selenium uses that Reference instead of finding the element again in the DOM. But sometimes due the AJAX request and responses this reference is no longer fresh, hence StaleElementReferenceException is thrown.

Lets see how this issue can be resolved, I know on the internet many people suggest to use the Lazy Initializer or the Page Object Model to minimize the Stale Element Exceptions. But this method is full proof and can work in any framework.

Solution:

public void clickElement(WebElement element)
{
    try
    {
        element.click();
    }catch(StaleElementReferenceException stale)
    {
        System.out.println("Element is stale. Clicking again");
        element = reInitializeStaleElement(element);
        element.click(); 
    }
}



//method to re-initialize the stale element
public WebElement reInitializeStaleElement(WebElement element)
{
    //lets convert element to string, so we can get it's locator
    String elementStr = element.toString();
    elementStr=elementStr.split("->")[1];

    String byType = elementStr.split(":")[0].trim();
    String locator = elementStr.split(":")[1].trim();
    locator=locator.substring(0,locator.length()-1);   


    switch(byType)
    {
        case "xpath":
            return DRIVER.findElement(By.xpath(locator));
        case "css":
            return DRIVER.findElement(By.cssSelector(locator));
        case "id":
            return DRIVER.findElement(By.id(locator));
        case "name":
            return DRIVER.findElement(By.name(locator));
    }
}

Enter fullscreen mode Exit fullscreen mode

The above code is only for reference, please don’t blindly copy it into your project.

Be smart enough to know how to use the driver instance in this method. I would suggest create a Singleton class for click methods or you can put this in to your TestUtil class depending on your framework design pattern.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player