Selenium Wait Until Page Loads

Profile picture for user arilio666

There is a method for waiting for a page until it is done loading and proceeding to the next step. This is done using a javascript executor loaded in selenium webdriver.

It is done using the javascript method or commands and with the help of the executescript method. Document.readyState is used as a parameter to the executeScript method and verifies if the value returned by this specified command is complete.

Syntax:

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

Example:

  • For example, we will check this out on autopractsite, where the page load is slow, and there is a popup that we will try to close after loading.
    WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("http://www.autopract.com");
        driver.manage().window().maximize();
        JavascriptExecutor j = driver;
        if (j.executeScript("return document.readyState").toString().equals("complete")) {
            System.out.println("Page has loaded");
        }
        driver.findElement(By.xpath("//button[@class='close']")).click();
Selenium Wait Until Page Loads
  • executeScript has returned for the document to wait for the ready state, and the state should return "Complete."
  • Only then is the block complete and waits until the page is loaded.