How to access to shadow DOM(open) using Selenium-webdriver

kaweesha wijayawickrama
3 min readJun 15, 2019

--

Document Object Model(DOM)

A Document Object Model(DOM) is a logical structure which represents a web page in HTML or XML (Here we proceed only about HTML DOM). DOM is platform and language independent. When automating web applications, we locate and perform actions on HTML elements in the DOM, using Selenium webdriver. Check the Selenium code in Java below.

Above line of code will return the first HTML element which has the value “example” to its id attribute within the opened web page.

When there is a shadow DOM in the main DOM, we can not directly locate HTML elements like above.

What is a shadow DOM?

Shadow DOM is a DOM within another DOM. Main DOM does not know that another DOM exits. Which means HTML elements, styles of the main DOM are not applied to the shadow DOM. Shadow-root is the document fragment which attaches the shadow DOM to the main DOM. When the shadow-root is attached to the main DOM, elements within the shadow-root become the shadow DOM.

When we try to locate HTML elements within a shadow DOM, webdriver throws org.openqa.selenium.NoSuchElementException. Because webdriver searches only within the main DOM. This is the problem that arises, when writing selenium test automation scripts to locate elements within a shadow DOM.

First we have to access the shadow-root of the shadow DOM.

Then we can access the elements within the shadow DOM from the shadow-root.

Important: We can not directly use xpath selector in the shadow DOM. It will throw org.openqa.selenium.InvalidSelectorException. But we can use id, name, className, cssSelector Selectors.

Example scenario:

Input “password” to search input field in Settings page — Chrome browser

(Chrome browser version used in this example is 75.0)

Check the DOM structure below.

Image 1
Image 2

According to the Image 1, there are 3 shadow-roots in the given DOM structure. Each shadow DOM resides in another shadow DOM. Input field is available in the third shadow DOM.

First we have to locate attached element of first shadow-root which is “settings-ui”.

Then we can locate the first shadow-root.

From the first shadow-root we can locate and access the attached element of second shadow-root.

Likewise we can access the elements of third shadow-DOM

After correctly locating third shadow-root, we can input the word to the search input field.

Result:

Image 3

Summary:

  • Shadow DOM is a DOM within another DOM. It can be a main DOM or a shadow DOM.
  • To access elements within a shadow DOM, we can use selenium webdriver javascriptExecutor.
  • First we have to locate the attached element of the shadow DOM. Then locate the shadow-root of shadow DOM using javascriptExecutor.

Refer following articles for more details

MDN — What is a DOM

www.tutorialrepublic.com — javascript-dom-nodes

--

--