Reputation: 76880
I saw that there is a question: Selenium-Webdriver Ruby --> How to wait for images to be fully loaded after click
But it seems that nobody has directly answered that: I need to wait for an image to be fully loaded, not just to present in the DOM, using selenium WebDriver. What should I do?Currently I'm using
public static void waitUntilVisible(WebDriver webDriver, By locator) {
WebDriverWait driverWait = new WebDriverWait(webDriver, TIMEOUT);
driverWait.until(visibilityOfElementLocated(locator));
}
which uses
/**
* An expectation for checking that an element is present on the DOM of a page and visible.
* Visibility means that the element is not only displayed but also has a height and width that is
* greater than 0.
*
* @param locator used to find the element
* @return the WebElement once it is located and visible
*/
public static ExpectedCondition<WebElement> visibilityOfElementLocated(
final By locator) {
return new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
try {
return elementIfVisible(findElement(locator, driver));
} catch (StaleElementReferenceException e) {
return null;
}
}
@Override
public String toString() {
return "visibility of element located by " + locator;
}
};
}
but if an image has already an height and width it's probably counted as visible even if the image hasn't loaded
Upvotes: 6
Views: 10813
Reputation: 1087
You could execute some javascript to interrogate the DOM. Specifically, the complete
property of an HTMLImageElement.
public static void waitUntilVisible(WebDriver webDriver, By locator) {
WebDriverWait driverWait = new WebDriverWait(webDriver, TIMEOUT);
WebElement el = webDriver.findElement(locator);
driverWait.until(
new Predicate<WebDriver>() {
public boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return arguments[0].complete", el);
}
}
);
}
But note that complete
:
Returns a Boolean that is true if the browser has finished fetching the image, whether successful or not. It also shows true, if the image has no src value.
Upvotes: 8