26. Handling Dynamic AJAX Elements & StaleElementReferenceException

Handling Spinners & Dynamic DOMs

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));

// 1. Wait for loading spinner to disappear:
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".loading-spinner")));

// 2. Retry loop for StaleElementReferenceException:
public static void clickWithStaleRetry(WebDriver driver, By locator, int maxRetries) {
int attempts = 0;
while (attempts < maxRetries) {
try {
driver.findElement(locator).click();
return;
} catch (StaleElementReferenceException e) {
attempts++;
}
}
throw new RuntimeException("Element remained stale after " + maxRetries + " attempts: " + locator);
}

Task

  • Implement waitForSpinnerToDisappear:
  • 1. Accept WebDriver driver and By spinnerLocator.
  • 2. Return new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.invisibilityOfElementLocated(spinnerLocator)).
πŸ’‘Common doubts
Did you like the problem?
Lesson 26 of 44
Java
Loading code editor…
Next