selenium-webdriver Wait Waiting For Ajax Requests to Complete


Example

C#

using OpenQA.Selenium
using OpenQA.Selenium.Chrome;
using System.Threading;

namespace WebDriver Tests
{
    class WebDriverWaits
    {
        static void Main()
        {
            IWebDriver driver = new ChromeDriver(@"C:\WebDriver");
            
            driver.Navigate().GoToUrl("page with ajax requests");
            CheckPageIsLoaded(driver);

            // Now the page is fully loaded, you can continue with further tests.
        }

        private void CheckPageIsLoaded(IWebDriver driver)
        {
            while (true)
            {
                bool ajaxIsComplete = (bool)(driver as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0");
                if (ajaxIsComplete)
                    return;
                Thread.Sleep(100);
            }
        }
    }
}

This example is useful for pages where ajax requests are made, here we use the IJavaScriptExecutor to run our own JavaScript code. As it is within a while loop it will continue to run until ajaxIsComplete == true and so the return statement is executed.

We check that all ajax requests are complete by confirming that jQuery.active is equal to 0. This works because each time a new ajax request is made jQuery.active is incremented and each time a request complements it is decremented, from this we can deduce that when jQuery.active == 0 all ajax requests must be complete.