πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
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