Selenium: StaleElementReferenceException

Problem:

StaleElementReferenceException. For example, when using: ((JavascriptExecutor)browser).executeScript("arguments[0].click();", this); 

Solution:

This exception seems to appear when performing actions on the same element multiple times and the element gets updated/reloaded between the actions.

This approach seemed to work (the idea is to catch the StaleElementReferenceException and make the element not stale but current by finding it again):

...
        int counter = 0;

        while (counter < maxClickAttempts) {
            try {
                 this.originalElement.click();

                Utils.waitForPageLoaded(browser);

                // exit the while-loop if there are no exceptions
                break;
                
                // if there is a StaleElementReferenceException then update the original element and repeat the click
                // (we assume AJAX/PPR as the cause)
            } catch (StaleElementReferenceException sere) {

                // update the element in case the page was fully or partially refreshed - to avoid another stale element exception
                // and to produce a successful click
                this.originalElement = (RemoteWebElement) browser.findElement(this.locator);
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
            
            counter++;
        }
...

Comments

Popular posts from this blog

Whitelist an Azure firewall IP using PowerShell

Excel: highlighting a row or a column based a value, the current date example.