Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium 2 wait until AJAX done in JAVA

I using Selenium 2 and Java 1.7. I want to wait my HtmlUnitDriver until ajax done when i clicked filter button.

My driver:

Webdriver driver = new HtmlUnitDriver(true);

Filter button and click action:

WebElement weFilterButton = driver.findElement(By.name("filterButton"));
weFilterButton.click();

I tried three ways for wait AJAX done.

first:

WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ctl00_ContentPlaceHolder1_Reports1_ajaxloadingImage"))); 

second:

Boolean el = wait.until(new ExpectedCondition<Boolean>() {
    public Boolean apply(WebDriver driver) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        return (Boolean) js.executeScript("return document.readyState").toString().equals("complete");
    }
});

and although it is not a good solution

driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

but is not work.

EDIT

Selenium dependency is :

<dependency>
     <groupId>org.seleniumhq.selenium</groupId>
     <artifactId>selenium-java</artifactId>
     <version>2.45.0</version>
</dependency> 
like image 381
renis Avatar asked Jun 27 '26 22:06

renis


1 Answers

Use the code below. It checks if the JQuery is active or not and wait till it is active.

Boolean isJqueryUsed = (Boolean)((JavascriptExecutor)driver).executeScript("return (typeof(jQuery) != 'undefined')"));
if(isJqueryUsed){
  while (true){
    // JavaScript test to verify jQuery is active or not
    Boolean ajaxIsComplete = (Boolean)(((JavascriptExecutor)driver).executeScript("return jQuery.active == 0"));
    if (ajaxIsComplete) break;
    try{
      Thread.sleep(100);
    }catch (InterruptedException e) {}
  }
}
like image 99
Manu Avatar answered Jun 30 '26 13:06

Manu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!