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:


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;
  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.

Author: Alister Scott

Alister is a Software Quality Engineer from Brisbane, Australia.

3 thoughts on “Waiting for AJAX calls in WebDriver C#”

  1. 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.

  2. Hi,
    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 jQuery.active == 0”));

    1. Yes, this achieves the same outcome.
      I personally like extension methods that can be called directly from the driver object as it makes my tests more readable.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s