This is a helper method we use in many places in our Selenium Java tests. The intent is to click a button and then detect that the browser has navigated away from the page by detecting the staleness of the HTML element:
protected static WebDriverWait wdWait;
public static void clickAndWaitForBrowserToLeavePage(WebElement elementToClick) {
WebElement htmlTag = wdWait.until(ExpectedConditions.presenceOfElementLocated(By.tagName(“html”)));
// click on the WebElement
elementToClick.click();
// wait until the <html> tag becomes stale
wdWait.until(ExpectedConditions.stalenessOf(htmlTag));
}
we also have this generalized version:
public static void clickAndWaitForElementToBecomeStale(WebElement elementToClick, WebElement elementToBecomeStale) {
// click on the WebElement to click
elementToClick.click();
// wait until the old WebElement becomes stale
wdWait.until(ExpectedConditions.stalenessOf(elementToBecomeStale));
}
The problem is that sometimes this script appears to not detect the staleness of the element it’s waiting to become stale, probably because it’s already stale before wdwait.until starts, and at that point it detects the same element on the next page, and obviously that’s not going to go stale because we don’t do anything on the new page before we finished this check.
Is there a way to avoid this “we’re waiting an element on the next page instead of an element on the page we just navigated away from” race condition while still retaining the “check we’ve actually refreshed the page”?
Source: Read More