Wait for an Ajax call to complete with Selenium 2 WebDriver.


We can wait for an Ajax call to complete with Selenium webdriver. The determination of the load time of the page due to an Ajax response is a difficult task. This can be achieved with the help of synchronization concepts and wait methods in Selenium. Some of them are listed below −

Implicit wait − It allows the web driver to wait for the time specified after which exception is thrown. This wait is applicable to all steps in the test.

Syntax

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

Example

Code Implementation with implicit wait.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class AjaxImplWt{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // wait for page load
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify element
      WebElement e=driver.findElement(By.className("gsc-input"));
      e.sendKeys("Java");
      driver.close();
   }
}

Ajax response call can also be handled with explicit wait. This wait is applied to a particular element. The wait for the specified time is done for some expected condition for an element. Exception is thrown, once the wait time has elapsed.

Example

Code Implementation with explicit wait.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AjaxWaitExplicit{
   public static void main(String[] args)
   throws InterruptedException{
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify element
      WebElement l=driver.findElement(By.xpath("//*[text()='Library']"));
      l.click();
      //explicit wait condition
      WebDriverWait wt = new WebDriverWait(driver,5);
      wt.until(ExpectedConditions.
      invisibilityOfElementLocated(By.xpath("//*[@class='mui-btn']")));
      driver.quit();
   }
}

We can also add custom ExpectedConditions for Selenium. We need custom ExpectedConditions when the default expected conditions provided by webdriver are not enough. The method until is used which is a part of the WebDriverWait class.

Example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AjaxCustomExpCondition{
   public static void main(String[] args)
   throws InterruptedException{
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement l=driver.findElement(By.linkText("Team"));
      l.click();
      //object of WebDriverWait class
      WebDriverWait w = new WebDriverWait(driver,7);
      //custom expected condition with until method
      w.until(new ExpectedCondition <Boolean> (){
         public Boolean apply(WebDriver driver) {
            //identify paragraph
            WebElement e= driver.findElement(By.tagName("p"));
            if (e!= null){
               //to check if paragraph is displayed and has text India
               if (e.isDisplayed() && e.getText().contains("India")) {
                  System.out.println("Element found");
                  return true;
               } else {
                  System.out.println("Element not found");
                  return false;
               }
            }
            return false;
         }
      });
      driver.close();
   }
}

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.

Example

Code Implementation with JavaScript.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;
public class AjaxJavaScrptWt{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      //wait with JavaScript Executor
      while (true){
         if ((Boolean) ((JavascriptExecutor)driver).
         .executeScript("return jQuery.active == 0")){
            break;
         }
         Thread.sleep(500);
      }
   }
}

Updated on: 30-Jan-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements