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();

Add comment

Loading