Back to All Scenarios
Scenario 21 of 100
Exceptions
Intermediate
Element Refreshed by JavaScript Re-locate
βοΈScenario Overview
Element Refreshed by JavaScript Re-locate
Key Takeaways & Cheat Sheet
- βDetect elements that are periodically updated by setInterval or AJAX timers
- βImplement a custom locator supplier or dynamic getter method
- βAvoid saving WebElements as class instance variables
- βUtilize short dynamic polling schedules in FluentWait
Short Direct Answer
When a web application uses background scripts to refresh page content at fixed intervals, located WebElements quickly become stale. To handle this, never store WebElement references as fields. Instead, implement them as dynamic getters or methods that execute `driver.findElement()` at the exact moment of interaction.
β οΈ Senior Warning (Red Flag)
Never store elements in a Page Object constructor. Constructors run once on page creation. If Javascript refreshes the element later, the reference is lost, causing stale exceptions.
π‘ STAR Deep Dive Explanation & Pro Tip
Using dynamic getters ensures that your Page Objects always query the current DOM state, eliminating stale element exceptions caused by background JS refreshes.
SeleniumAutomation.java
Selenium 4 + Java// β POOR: Storing element in constructor
// public MyPage(WebDriver driver) { this.submitButton = driver.findElement(By.id("sub")); }
// β
BEST: Define a dynamic getter method
public WebElement getSubmitButton() {
return driver.findElement(By.id("sub-button"));
}
// Usage:
getSubmitButton().click(); // Always locates fresh element