Wait for page load in Selenium WebDriver with Java

We might need to wait after loading a web page, after clicking some link or performing any action that requires some time for the page to get loaded.

And on the other hand, we do not know the amount of time that we need to wait for as it varies from application to application.

Let’s have a look at the mechanism which waits for page to load before performing any further action.

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WaitForPageLoad {

             public static void main(String[] args) throws Exception {
                          WebDriver driver = new FirefoxDriver();
                          driver.get(“http://google.com”);
                          driver.manage().window().maximize();
                         

                         // calling the method which handles wait for page to load

                         waitForPageLoad(driver, 30);
                         driver.findElement(By.id(“lst-ib”)).sendKeys(“Selenium”);

                }

             private static void waitForPageLoad (WebDriver driver, int timeout) {
                         ExpectedCondition<Boolean> condition = new ExpectedCondition<Boolean>() {
                         public Boolean apply(WebDriver driver) {
                                      return ((JavascriptExecutor) driver).executeScript(“return document.readyState”).equals(“complete”);
                          }
                };

                WebDriverWait wait = new WebDriverWait(driver, timeout);
                wait.until(condition);
          }
}

Code explanation :

waitForPageLoad(WebDriver driver, int timeout) – The method accepts the current driver instance and the timeout value in seconds.

We have written a custom ExpectedCondition that returns TRUE when document.readySyate is complete i.e. the web page is loaded completely.

And lastly, we have created an instance of WebDriverWait, waiting until custom condition written returns TRUE till specified timeout (i.e. web page is loaded).

Hope it works for you !!

Cheers 🙂

Advertisements

#expectedconditions, #readystate, #waitforpageload