Redgard
Redgard

Reputation: 11

Selenium Java (proper wait for new page to load)

It's not a question but rather a sharing of information (i think many people will use it)

For few days tried to make one best solution (without sheninigans :-D ) to wait for new page to load, after click etc. Ofc no old days Thread.sleep or implicit waits

Some people suggested to wait until a last element from new page loads, some suggested to use JS executor (document.readyState solution) which will sometimes not work (in my case, it was always giving complete response)

Found another solution, to check when a reference to element on current page will throw StaleElementReferenceException. But... in this case the page didn't manage to load after this exception.

What i did? combined both solutions together and this always does a trick for me... One make sure that document isn't in a ready state (cause throws staleElementReferenceException) and another immediately after that checks till the page fully loads and gives readyState == complete

    while(true) {    
       try {
          //it's just an interaction (can be any) with element on current page
          anyElementFromCurrentPage.getText();
       } catch (StaleElementReferenceException e) {
            break;
       }
       waitForLoad(driver);
       return this;
    }

    void waitForLoad(WebDriver driver) {
       new WebDriverWait(driver, 30).until((ExpectedCondition<Boolean>) wd ->
                    ((JavascriptExecutor) wd).executeScript("return 
       document.readyState").equals("complete"));
    }

hope some people will use this bulletproof solution :-)

Upvotes: 0

Views: 55

Answers (1)

William.Avery
William.Avery

Reputation: 70

So I work in C# but Java is similar. This is currently what I use even though its marked as "obsolete".

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Name("elementNameHere")));

Upvotes: 0

Related Questions