How to: Selenium wait for AJAX response

We can find a many questions on web about problem how to get Selenium wait for AJAX response. Programmer wants to write a code, where is important to wait for complete load state of page. Sometimes you can see that page have been loaded, but some fields are not filled, because there are unfinished AJAX requests without responses. If you are able to check loading element (for example gif loader), you can do it easily via findElement. But if there is not any loading indicator, you have only one chance how to resolve it. JavaScript! Google can give you a huge amount of results, jQuery.active etc…. nothing worked for me. So here is solution:

public static void waitForAjax(WebDriver driver, String action) {
       driver.manage().timeouts().setScriptTimeout(5, TimeUnit.SECONDS);
       ((JavascriptExecutor) driver).executeAsyncScript(
               "var callback = arguments[arguments.length - 1];" +
                       "var xhr = new XMLHttpRequest();" +
                       "xhr.open('POST', '/" + action + "', true);" +
                       "xhr.onreadystatechange = function() {" +
                       "  if (xhr.readyState == 4) {" +
                       "    callback(xhr.responseText);" +
                       "  }" +
                       "};" +
                       "xhr.send();");
}

You can call this method before you want to check a field (or during loading method – i am using onLoad ). Call this method with driver as first parameter and AJAX request call as String. It will set scripting timeout at first and execute JS asynchronous script.

You can use it by calling this static method like this:

waitForAjax(driver, "Ajax_call");

As driver you have to use actual WebDriver (for example: WebDriver driver = new FirefoxDriver(); – this will return you actual driver – Selenium-WebDriver makes direct calls to the browser using each browser’s native support for automation) and as Ajax_method you pass the name of Ajax calling. You can open page and via Developer tools of web browser find a name of call in Resources. This will help you only if you know on which Ajax call you are waiting.

I hope that this will help you and save your time.

Aleš Laňar
Senior Engineer Software ve společnosti CA Technologies

2 thoughts on “How to: Selenium wait for AJAX response

  1. Hello,

    I found the article very interesting and I have one doubt regarding the method.

    What is the value of action you are passing in the method? Like what should I pass there and how to identify what is the action. For example, my Request looks like this:

    Request URL: https://my.domain.io/?action

    I am not sure what should I send in place of Action in your method.

    1. Thank you.
      I edited your comment to remove URL.
      So if your request is on this URL, put this Request URL as String in second parameter.

Leave a Reply

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