Introduction
Shadow DOM hides parts of a webpage to keep them separate. Accessing Shadow DOM elements lets you test or interact with these hidden parts.
WebElement shadowHost = driver.findElement(By.cssSelector("shadow-host-selector")); SearchContext shadowRoot = shadowHost.getShadowRoot(); WebElement shadowElement = shadowRoot.findElement(By.cssSelector("shadow-element-selector"));
getShadowRoot() on the shadow host element to get inside the Shadow DOM.findElement on the shadow root to access elements inside Shadow DOM.my-component and clicks it.WebElement shadowHost = driver.findElement(By.cssSelector("my-component")); SearchContext shadowRoot = shadowHost.getShadowRoot(); WebElement button = shadowRoot.findElement(By.cssSelector("button.submit")); button.click();
WebElement shadowHost = driver.findElement(By.id("shadow-host")); SearchContext shadowRoot = shadowHost.getShadowRoot(); WebElement input = shadowRoot.findElement(By.cssSelector("input[name='email']")); input.sendKeys("user@example.com");
import org.openqa.selenium.By; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class ShadowDomAccess { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://shop.polymer-project.org/"); // Find the shadow host element WebElement shopApp = driver.findElement(By.tagName("shop-app")); // Access shadow root SearchContext shadowRoot = shopApp.getShadowRoot(); // Find element inside shadow DOM WebElement cartButton = shadowRoot.findElement(By.cssSelector("a[href='/cart']")); // Print the text of the cart button System.out.println("Cart button text: " + cartButton.getText()); } finally { driver.quit(); } } }
getShadowRoot() (Selenium 4+).getShadowRoot() on the shadow host element to access inside Shadow DOM.findElement on the shadow root to find elements inside Shadow DOM.driver.findElement(By.id("shadowHost")) to get the host element.getShadowRoot() on the host, then find the button inside the shadow root.WebElement host = driver.findElement(By.id("shadowHost"));
WebElement shadowRoot = host.getShadowRoot();
WebElement button = shadowRoot.findElement(By.cssSelector("button"));
System.out.println(button.getText());getShadowRoot() to access the Shadow DOM.getText() returns its visible text 'Click Me'.WebElement button = driver.findElement(By.cssSelector("#shadowHost button"));
button.click();getShadowRoot() on the host element before finding inner elements.getShadowRoot() to access its Shadow DOM.getShadowRoot() again to access the inner Shadow DOM.click() on it.Pass the test and this pattern moves unknown