One important thing to note is that the driver.navigate().refresh() call sometimes seems to be asynchronous, meaning it does not wait for the refresh to finish, it just "kicks off the refresh" and doesn't block further execution while the browser is reloading the page.
While this only seems to happen in a minority of cases, we figured that it's better to make sure this works 100% by adding a manual check whether the page really started reloading.
Here's the code I wrote for that in our base page object class:
public void reload() {
// remember reference to current html root element
final WebElement htmlRoot = getDriver().findElement(By.tagName("html"));
// the refresh seems to sometimes be asynchronous, so this sometimes just kicks off the refresh,
// but doesn't actually wait for the fresh to finish
getDriver().navigate().refresh();
// verify page started reloading by checking that the html root is not present anymore
final long startTime = System.currentTimeMillis();
final long maxLoadTime = TimeUnit.SECONDS.toMillis(getMaximumLoadTime());
boolean startedReloading = false;
do {
try {
startedReloading = !htmlRoot.isDisplayed();
} catch (ElementNotVisibleException | StaleElementReferenceException ex) {
startedReloading = true;
}
} while (!startedReloading && (System.currentTimeMillis() - startTime < maxLoadTime));
if (!startedReloading) {
throw new IllegalStateException("Page " + getName() + " did not start reloading in " + maxLoadTime + "ms");
}
// verify page finished reloading
verify();
}
Some notes:
- Since you're reloading the page, you can't just check existence of a given element, because the element will be there before the reload starts and after it's done as well. So sometimes you might get true, but the page didn't even start loading yet.
- When the page reloads, checking WebElement.isDisplayed() will throw a StaleElementReferenceException. The rest is just to cover all bases
- getName(): internal method that gets the name of the page
- getMaximumLoadTime(): internal method that returns how long page should be allowed to load in seconds
- verify(): internal method makes sure the page actually loaded
Again, in a vast majority of cases, the do/while loop runs a single time because the code beyond navigate().refresh() doesn't get executed until the browser actually reloaded the page completely, but we've seen cases where it actually takes seconds to get through that loop because the navigate().refresh() didn't block until the browser finished loading.