Need to wait until page is completely loaded - Selenium WebDriver


We can wait until the page is completely loaded in Selenium webdriver by using the JavaScript Executor. Selenium can run JavaScript commands with the help of the executeScript method.

We have to pass return document.readyState as a parameter to the executeScript method and then verify if the value returned by this command is complete.

Syntax

JavascriptExecutor j = (JavascriptExecutor)driver;
if (j.executeScript("return document.readyState").toString().equals("complete")){
   System.out.println("Page has loaded");
}

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class PageLdWait{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      // JavaScript Executor to check ready state
      JavascriptExecutor j = (JavascriptExecutor)driver;
      if (j.executeScript("return document.readyState").toString().equals("complete")){
         System.out.println("Page has loaded");
      }
      //iterate 50 times after every one second to verify if in ready state
      for (int i=0; i<50; i++){
         try {
            Thread.sleep(1000);
         }catch (InterruptedException ex) {
            System.out.println("Page has not loaded yet ");
         }
         //again check page state
         if (j.executeScript("return document.readyState").toString().equals("complete")){
            break;
         }
      }
   }
}

Output

Updated on: 06-Apr-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements