Waiting for AJAX calls in WebDriver C#

I was trying to work out how to wait for AJAX calls to complete in C# WebDriver before continuing a test.

Whilst I believe that your UI should visually indicate that AJAX activity is occurring (such as a spinner) and in this case you should be able to wait until such an indicator changes, if you don’t have a visual indicator and you use JQuery for your AJAX calls, you can use a JavaScript call to jQuery.active to determine if there are any active AJAX requests, and wait until this value is zero.

I wrapped this into a WebDriver extension method on Driver, so you can call it like this:

Driver.FindElement(By.Id("name")).Set("Alister");
Driver.WaitForAjax();
Driver.FindElement(By.Id("next")).Click();

The actual extension method looks like this:

public static void WaitForAjax(this IWebDriver driver, int timeoutSecs = 10, bool throwException=false)
{
  for (var i = 0; i < timeoutSecs; i++)
  {
    var ajaxIsComplete = (bool)(driver as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0");
    if (ajaxIsComplete) return;
    Thread.Sleep(1000);
  }
  if (throwException)
  {
    throw new Exception("WebDriver timed out waiting for AJAX call to complete");
  }
}

I hope you find this helpful if you’re ever in the same situation.