Automated Testing WebDriver

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 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:


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 == 0");
    if (ajaxIsComplete) return;
  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.

0 replies on “Waiting for AJAX calls in WebDriver C#”

I’ll be trying this out, but here we’ve got a spinner (affectionately called the ‘fascinator’), of which I detect the absence, wrapped up method like this:


The condition for progressing past the method is when this returns != True

This relies on a common classname being used throughout the codebase, and also relies on all ajax activity to have ceased before the fascinator goes, things which I’m not able to mandate (sadly).

I think your .active way will solve this.

Would it not be possible to use this with an explicit wait?

For example:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(d => (bool)(d as IJavaScriptExecutor).ExecuteScript(“return == 0”));

Leave a Reply

Your email address will not be published. Required fields are marked *