How to wait for page to load completely using JavaScript in Selenium

8.4k views Asked by At

I'm trying get for page to load completely before doing an action. I don't want to start an action while loading circle on the browser tab is still turning. My wait for ajax function is not working for some cases, especially for new page loading. My function is JQuery based:

JavascriptExecutor jsDriver = (JavascriptExecutor) webDriver;
boolean stillRunningAjax = (Boolean) jsDriver
        .executeScript("return window.jQuery != undefined && jQuery.active != 0");
return !stillRunningAjax;

if that comes false, running it again.

But for page loading, after it returns true, browser is still loading (loading circle is turning) for a couple of seconds more (sometimes much more).

I've tried implicitlyWait but it stops the function at the same time with my function.

Some says there is not a complete solution for this in selenium. But there should be. Maybe a JavaScript included solution, anything.

1

There are 1 answers

7
ingrid.e On

Using javascript to wait for page to load:

void waitForLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
    ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver driver) {
            return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
        }
    };
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}

If you're waiting for an ajax to display an element on page, you can wait for the element itself.

WebElement myDynamicElement = (new WebDriverWait(driver, 10))
 .until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));