2

I am using Selenium WebDriver and FirefoxDriver to automate an old website. The website was built using plain JavaScript. It is using XMLHttpRequest to perform Ajax requests. I want to write a function WaitForAjax() that should wait for the Ajax request to complete. Currently, I am using Explicit Wait (Thread.Sleep) to accomplish it. Can anyone help me to accomplish the same with Implicit Wait?

protected void WaitForAjax() {
    /*  
     while (true) {
         var ajaxIsComplete = (bool)(_driver as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0");
         if (ajaxIsComplete)
             break;
     }
     */

    //I am using Explicit Waits of 3 second.
    Thread.Sleep(TimeSpan.FromSeconds(3));
}
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
  • https://stackoverflow.com/questions/15122864/selenium-wait-until-document-is-ready you can try to check ready state of web page – Ankur Singh Dec 26 '17 at 13:06

1 Answers1

0

Never use Thread.sleep() unless there is nothing else to do. And in most cases, there is something to do :) You can try a script like this:

public void waitForAjax() {
    ExpectedCondition<Boolean> pageLoadCondition = driver -> "complete".equals(((JavascriptExecutor) driver).executeScript("return document.readyState"));
    WebDriverWait wait = new WebDriverWait(webDriver, 30);
    wait.until(pageLoadCondition);
}
Taylan Derinbay
  • 128
  • 3
  • 13
  • As I already mentioned that the website I am automating is not using jQuery. Its using XMLHttpRequest to send ajax request. – Binny Chanchal Dec 26 '17 at 14:05
  • Sorry for that, I've edited the method. I'm using java by the way, I saw that you asked for C#, but the idea is same. An explicit wait for an expected condition of "document.readyState" – Taylan Derinbay Dec 27 '17 at 14:36
  • thanks for your response. I checked your solution, but document.readyState does not ensure completion of the Ajax request. As per MDN document (https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState), document.readyState== 'complete' that the document and all sub-resources have finished loading. It's helpful to check PageLoad. As per this answer( https://stackoverflow.com/a/15136386/7875155), there is no generic way of checking the Ajax. – Binny Chanchal Dec 28 '17 at 08:06
  • 1
    If you want to wait all asynchronous loads to finish, that's right. There is no way to do that, selenium recommends to use expected conditions for next action. – Taylan Derinbay Dec 28 '17 at 08:38