Access Shadow DOM Elements

What is Shadow DOM
Shadow DOM is an emerging standard for encapsulating DOM and styling, with composition. In another word: via Shadow DOM a Web Developer can hide details of certain web component from peer developers. The developer cannot access the Shadow DOM in the same way we would with nested elements, while the browser can render and modify that code the same way it would with nested elements.

Browser includes shadow DOM component as subtree of DOM elements into the rendering of a document, but not into the main document DOM tree. Browsers that support Shadow DOM: Chrome, Firefox and Safari.

Shadow DOM element looks no different than any other normal web elements on surface, but if we inspect it in browser’s console, it looks like this:

Figure 1: Shadow DOM

Shadow DOM elements are not accessible to Selenium WebDriver. We have to use javascript for access:

//First, find the element that encapsulates the shadow DOM
WebElement wrappingElement = driver.findElement(By.tagName(“downloads-manager”));

//Then get shadow root using javascript
String script = “return arguments[0].shadowRoot”;
WebElement shadowDOM = (WebElement) ((JavascriptExecutor) driver).executeScript(script,wrappingElement);

//Then access individual element inside shadow DOM as usual:
WebElement toolbar = driver.findElement(By.id(“toolbar”));

Leave a Reply

Your email address will not be published. Required fields are marked *