Automating Shadow DOM

Snehal Salunke
helpshift-engineering
3 min readAug 30, 2022

While writing the automation test script for a hybrid app using Appium, I encountered the challenge of handling Shadow DOM web elements. Appium, which derives its roots from Selenium, does not provide explicit support for working with Shadow DOM elements. If you try to find out shadow DOM element with locators, you will get “NoSuchElementException”. To access these elements, we need to use the JavascriptExecutor executeScript() function.

Let’s understand what shadow DOM is?

Shadow DOM serves for encapsulation. It allows a component to have its very own “shadow” DOM tree, that can’t be accidentally accessed from the main document, may have local style rules, and more.

Visual representation of Shadow DOM

This is the visual representation of how Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree.

There are some bits of shadow DOM terminology -
Shadow host: The regular DOM node that the shadow DOM is attached to.
Shadow tree: The DOM tree inside the shadow DOM.
Shadow boundary: the place where the shadow DOM ends, and the regular DOM begins.
Shadow root: The root node of the shadow tree.

Explore Shadow DOM with example

We will look into Helpshift’s Help Center page, where FAQ Article feedback section is inside shadow root.

Here, the left side image shows the FAQ article screen of the hybrid mobile app and on the right side you can see to get FAQ feedback questions or FAQ feedback buttons. To access these elements, we need to navigate through the shadow root element.
We can access the elements only if shadow-root DOM has open mode.

Find shadow root element via Console

To achieve this, we can use the console to traverse to the root element as above. Once we can traverse until our required path, we will get the WebElement of shadow-root using JavascriptExecutor executeScript() function inside our page classes to perform actions on that web element.

Code snippet: Click FAQ feedback button which is inside shadow root

The shadow-root handling is encapsulated in the page classes, which make the test scripts easier to read, and more importantly, easier to maintain.

Happy testing!

--

--