How to fix the ChromeDriver StaleElementReferenceException issue

Problem:

I have a Selenium test that works perfectly with the Firefox and Internet Explorer drivers but I get the following error when using the Chrome driver:

OpenQA.Selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

Solution:

Wait for navigation to next page.

var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30));

wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

Explanation:

In my case I was simply trying to click a series of links in the web sites navigation.  The code in the test just found the link and clicked it.  However, all the links I wanted to click were always visible so after clicking the first link the Chrome driver found the second link to click before it navigated. Therefore, when it attempted to click the link we were on the next page where this item was now stale.  The other drivers I tested all worked as expected.  So I decided to use the code above to force the test to wait for the navigation to complete before attempting to find the next link to click.

You can make this very easy to use by creating an extension method for the IWebDriver interface.

public static class SeleniumExtensions

{

   public static void WaitForNavigation(this IWebDriver driver)

   {

      var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30));

      wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

   }

}

Now you can call WaitForNavigation on your driver object whenever you know your test would navigate to another page. This will allow the test to wait for the next page to load before continuing to run the test.

driver.FindElementByLinkText("About").Click();

driver.WaitForNavigation();

driver.FindElementByLinkText("Contact").Click();

driver.WaitForNavigation();

driver.FindElementByLinkText("Home").Click();

Comments (1) -

  • cezarypiatek

    10/2/2017 3:44:15 PM | Reply

    Hi Donovan

    I think that your solution may be missing many other cases when selenium throws StaleElemenetReferenceException. . I got the idea of StableWebElement - a wrapper which could detect Stale reference situation and try to find a new reference to the original element. All method for locating WebElement in my test always return StableWebElement wrapper and the problem with StaleObjectReferenceException disappeared.
    If you are interested, a working solution implementation is available on my github project in this class github.com/.../StableWebElement.cs

Add comment

Loading