Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium wait for Ajax content to load - universal approach

Tags:

Is there a universal approach for Selenium to wait till all ajax content has loaded? (not tied to a specific website - so it works for every ajax website)

like image 325
Fabian Lurz Avatar asked Oct 26 '15 14:10

Fabian Lurz


People also ask

How wait for Ajax call in Selenium?

Moreover, the JavaScript Executor can be used to wait for an Ajax call. The executeScript method is used to run a JavaScript command in Selenium. The waiting is done till jQuery. active command yields 0.

Which wait mechanism is used for Ajax controls?

Implicit Wait() This method tells webdriver to wait if the element is not available immediately, but this wait will be in place for the entire time the browser is open.

Which is the best wait in Selenium?

The best practice to wait for a change in Selenium is to use the synchronization concept. The implicit and explicit waits can be used to handle a wait. The implicit is a global wait applied to every element on the page. The default value of implicit wait is 0.


2 Answers

You need to wait for Javascript and jQuery to finish loading. Execute Javascript to check if jQuery.active is 0 and document.readyState is complete, which means the JS and jQuery load is complete.

public boolean waitForJSandJQueryToLoad() {      WebDriverWait wait = new WebDriverWait(driver, 30);      // wait for jQuery to load     ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {       @Override       public Boolean apply(WebDriver driver) {         try {           return ((Long)((JavascriptExecutor)getDriver()).executeScript("return jQuery.active") == 0);         }         catch (Exception e) {           // no jQuery present           return true;         }       }     };      // wait for Javascript to load     ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {       @Override       public Boolean apply(WebDriver driver) {         return ((JavascriptExecutor)getDriver()).executeScript("return document.readyState")         .toString().equals("complete");       }     };    return wait.until(jQueryLoad) && wait.until(jsLoad); } 
like image 75
LINGS Avatar answered Oct 06 '22 00:10

LINGS


As Mark Collin described in his book "Mastering Selenium Webdriver", use JavascriptExecutor let you figure out whether a website using jQuery has finished making AJAX calls

public class AdditionalConditions {    public static ExpectedCondition<Boolean> jQueryAJAXCallsHaveCompleted() {     return new ExpectedCondition<Boolean>() {          @Override         public Boolean apply(WebDriver driver) {             return (Boolean) ((JavascriptExecutor) driver).executeScript("return (window.jQuery != null) && (jQuery.active === 0);");         }     };   } } 
like image 36
Slav Kurochkin Avatar answered Oct 05 '22 22:10

Slav Kurochkin