简体   繁体   中英

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

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.

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")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM