34. Shadow DOM Elements & Selenium 4 getShadowRoot()

Automating Open Shadow DOM in Selenium 4

Standard XPath does not pierce Shadow DOM! You must locate the shadow host, obtain the SearchContext via getShadowRoot(), and locate inner elements via CSS selectors:
import org.openqa.selenium.SearchContext;

// 1. Locate shadow host element:
WebElement shadowHost = driver.findElement(By.cssSelector("#custom-dropdown-host"));

// 2. Get shadow root context:
SearchContext shadowRoot = shadowHost.getShadowRoot();

// 3. Find element inside shadow root using CSS:
WebElement internalBtn = shadowRoot.findElement(By.cssSelector("button.select-btn"));
internalBtn.click();

Task

  • Implement findElementInShadowRoot:
  • 1. Accept WebElement shadowHost and By cssLocator.
  • 2. Return shadowHost.getShadowRoot().findElement(cssLocator).
πŸ’‘Common doubts
Did you like the problem?
Lesson 34 of 44
Java
Loading code editor…
Next