How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (2023)

The DOM is the collection of elements in a document and their properties, like id, class, and style. You can think of a shadow DOM as something similar to a DOM, but inside it are hidden or encapsulated things that you can't see unless you look closely."} }]}

I came across one of the test cases in my previous projects where I had to click on a button to navigate to the next page. I searched for the element locator of the button on the page and ran the tests hoping it would click the button and navigate to the next page.

But to my surprise, the test failed as it couldn’t locate the element, and I received NoSuchElementException in the console logs. I was not happy to see that error as it was a simple button that I was trying to click, and there was no complexity.

On analyzing the issue further, expanding the DOM, and checking the root elements, I found that the button locator was inside the #shadow-root(open) tree node, which made me realize that it needs to be handled in a different way as it is a Shadow DOM element.

In this Selenium WebDriver tutorial, we will discuss Shadow DOM elements and how to automate Shadow DOM in Selenium WebDriver. Before we move on to automating Shadow DOM in Selenium, let’s first understand what Shadow DOM is? and Why is it used?

TABLE OF CONTENTS

  • What is Shadow DOM?
  • What is the usage of Shadow DOM?
  • Finding Shadow DOM elements using Selenium WebDriver
  • How to find Shadow DOM in Selenium WebDriver using the ‘getShadowDom’ method?
  • How to find Shadow DOM in Selenium using JavaScriptExecutor?
  • Frequently Asked Questions (FAQs)

What is Shadow DOM?

Shadow DOM is a functionality that allows the web browser to render DOM elements without putting them into the main document DOM tree. This creates a barrier between what the developer and the browser can reach; the developer cannot access the Shadow DOM the same way they would with nested elements, while the browser can render and modify that code the same way it would with nested elements.

The Shadow DOM is a way to achieve encapsulation in the HTML document. By implementing it, you can keep the style and behavior of one part of the document hidden and separate from the other code of the same document so that there is no interference.

Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — the Shadow DOM tree starts with a Shadow root, underneath which you can attach any element in the same way as the normal DOM.

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (1)

There are some bits of Shadow DOM terminology to be aware of:

  • Shadow host: The regular DOM node to which the Shadow DOM is attached.
  • 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.

Watch this video to learn what Shadow DOM is and how to automate it using Selenium WebDriver.

What is the usage of Shadow DOM?

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

Here are some of the essential properties of Shadow DOM:

  • Have their own ids space.
  • Invisible to JavaScript selectors from the main document, such as querySelector.
  • Use styles only from the shadow tree, not from the main document.

Finding Shadow DOM elements using Selenium WebDriver

When we try to find the Shadow DOM elements using Selenium locators, we get NoSuchElementException as it is not directly accessible to the DOM.

We would use the following strategy to access the Shadow DOM locators:

  1. Using JavaScriptExecutor.
  2. Using Selenium WebDriver’s getShadowDom() method.

In this section of this blog on automating Shadow DOM in Selenium, let’s take an example of Watir.com’s Homepage and try to assert the shadow dom and the nested shadow dom text with Selenium WebDriver. Note, it has 1 shadow root element before we reach text -> some text, and there are 2 shadow root elements before we reach the text -> nested text.

HomePage of Watir.com

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (2)

Figure 1

Now, if we try to locate the element using the cssSelector(“#shadow_content > span”), it
doesn’t get located, and Selenium WebDriver will throw NoSuchElementException.

Here is the screenshot of the Homepage class, which has the code which tries to get text using
cssSelector(“#shadow_content > span”).

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (3)

Here is the screenshot of the tests where we try to assert the text(“some text”).

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (4)

Error on Running the tests shows NoSuchElementException

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (5)

To locate the element correctly for the text, we need to go through the Shadow root elements. Only then would we be able to locate “some text” and “nested text” on the page.

Automate your Java test scripts across 3000+ real browsers and OS. Try LambdaTest Now!

How to find Shadow DOM in Selenium WebDriver using the ‘getShadowDom’ method?

With the release of Selenium WebDriver’s version 4.0.0 and above, the getShadowRoot() method was introduced and helped locate Shadow root elements.

Here is the syntax and details of the getShadowRoot() method:

1

2

3

4

5

6

7

default SearchContext getShadowRoot()

Returns:

The ShadowRoot class represents the shadow root of a web component. With a shadow root, you can access the shadow DOM of a web component.

Throws:

NoSuchShadowRootException - If shadow root is not found.

As per the documentation, the getShadowRoot() method returns a representation of an element’s Shadow root for accessing the Shadow DOM of a web component.

In case Shadow root is not found, it will throw NoSuchShadowRootException.

Before we begin writing the tests and discussing the code, let me tell you about the tools we would use to write and run the tests:

The following programming language and tools have been used in writing and running the tests:

  • Programming Language: Java 11.
  • Web Automation Tool: Selenium WebDriver.
  • Test Runner: TestNG.
  • Build Tool: Maven.
  • Cloud Platform: LambdaTest.

Getting Started with finding Shadow DOM in Selenium WebDriver

As discussed earlier, this project on Shadow DOM in Selenium has been created using Maven. TestNG is used as a test runner. To learn more about Maven, you can go through this blog on getting started with Maven for Selenium testing.

Once the project is created, we need to add the dependency for Selenium WebDriver, and TestNG in the pom.xml file.

Versions of the dependencies are set in a separate properties block. This is done for maintainability, so if we need to update the versions, we can do it easily without searching the dependency throughout the pom.xml file.

GitHub

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (6)

Let’s move on to the code now, the Page Object Model (POM) has been used in this project as it is useful in reducing code duplication and improves test case maintenance.

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (7)

First, we would be finding the locator for “some text” and “nested text” on HomePage.

FileName – HomePage class

Code Walkthrough

getShadowDomText() method:

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (8)

(Video) SelectorsHub: How to Automate Shadow DOM & Nested Shadow DOM Elements in Selenium?

The first element that we would be locating is the < div id = "shadow_host" > by using locator strategy – id.

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (9)

1

WebElement shadowHost = getDriver ().findElement (By.id ("shadow_host"));

Next we search for the first Shadow Root in the DOM next to it. For this, we have used the SearchContext interface. The Shadow Root is returned using the getShadowRoot() method. If you check in the screenshot above, #shadow-root (open) is next to the < div id = "shadow_host" >.

For locating the text – “some text” there is only one Shadow DOM element we need to get through.

The following line of code helps us get the Shadow root element.

1

SearchContext shadowRoot = downloadsManager.getShadowRoot();

Once Shadow Root is found, we can search for the element to locate the text – “some text”. The following line of code helps us get the text:

1

2

String text = shadowRoot.findElement (By.cssSelector ("#shadow_content > span"))

.getText ();

Next, let’s find the locator of “nested text” which has a nested Shadow root element and let’s find out how to locate its element.

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (10)

getNestedShadowText() method:

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (11)

Starting from the top, as discussed in the above section, we need to locate
< div id = "shadow_host" > by using locator strategy – id.

1

WebElement shadowHost = getDriver ().findElement (By.id ("shadow_host"));

After that we need to find the Shadow Root element by using the getShadowRoot() method, once we get the Shadow root element we will need to get into the finding the second Shadow root by using cssSelector for locating:

(Video) How To Handle Shadow DOM Using Selenium

1

<div id ="nested_shadow_host">

1

2

SearchContext shadowRoot = shadowHost.getShadowRoot ();

WebElement shadowContent = shadowRoot.findElement (By.cssSelector ("#nested_shadow_host"));

Next we need to find the second Shadow Root element by using the getShadowRoot() method. Finally, it is time to locate the actual element for getting the text – “nested text”.
Following line of code will help us in locating text:

1

2

SearchContext shadowRootTwo = shadowContent.getShadowRoot ();

String nestedText = shadowRootTwo.findElement (By.cssSelector ("#nested_shadow_content > div")).getText ();

Writing the code in a fluent way

In the above section of this blog on Shadow DOM in Selenium, we saw a long way from where we have to locate the actual element we want to work with, and we have to do multiple initializations of WebElement and SearchContext interfaces and write multiple lines of code to locate a single element to work with.

We have a fluent way of writing this whole code as well. And here it is how you can do that:

1

2

3

4

5

6

7

8

public String getNestedText() {

WebElement nestedText = getDriver ().findElement (By.id ("shadow_host"))

.getShadowRoot ()

.findElement (By.cssSelector ("#nested_shadow_host"))

.getShadowRoot ()

.findElement (By.cssSelector ("#nested_shadow_content > div"));

return nestedText.getText ();

}

Fluent Interface’s design relies extensively on method chaining. A Fluent Interface pattern helps us write an easy-readable code that can be understood without putting effort into technically understanding the code. This term was coined first in 2005 by Eric Evans and Martin Fowler.

This is a method of chaining we would be performing to locate the element.

This code does the same thing as we did in the above steps.

  1. First, we would be locating the shadow_host element by using its id, after which we would get the Shadow Root element using the getShadowRoot() method.
  2. Next, We would search for the nested_shadow_host element using the cssSelector and get the Shadow Root element using the getShadowRoot() method.
  3. Finally, we would get the “nested text” text by using the cssSelector – nested_shadow_content > div.

How to find Shadow DOM in Selenium using JavaScriptExecutor?

In the above code examples, we located elements using the getShadowRoot() method. Let’s now see how we can locate the Shadow root elements using JavaScriptExecutor in Selenium WebDriver.

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (12)

getNestedTextUsingJSExecutor() method has been created inside the HomePage Class,
where we would be expanding the Shadow Root element based on the WebElement we pass in the parameter. Since in the DOM(as shown in the screenshot above), we saw that there are two Shadow Root elements we need to expand before we get to the actual locator for getting the text – nested text. Hence, the expandRootElement() method is created instead of copy-pasting the same javascript executor code every time.

We would implement the SearchContext interface, which would help us with the JavaScriptExecutor and return the Shadow root element based on the WebElement we pass in the parameter.

(Video) How To Handle Shadow DOM In Selenium 🤔| Selenium 4 Tutorial With Java | LambdaTest

1

2

3

4

5

public SearchContext expandRootElement (WebElement element) {

SearchContext shadowRoot = (SearchContext) ((JavascriptExecutor) getDriver ()).executeScript (

"return arguments[0].shadowRoot", element);

return shadowRoot;

}

getNestedTextUsingJSExecutor() method:

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (13)

The first element that we would be locating is the < div id = "shadow_host" > by using locator strategy – id

Next we would be expanding the Root Element based on the shadow_host WebElement we searched for.

1

2

WebElement shadowHost = getDriver ().findElement (By.id ("shadow_host"));

SearchContext shadowRootOne = expandRootElement (shadowHost);

After expanding the Shadow Root one, we can search for another WebElement using cssSelector for locating:

1

<div id ="nested_shadow_host">

1

2

WebElement nestedShadowHost = shadowRootOne.findElement (By.cssSelector ("#nested_shadow_host"));

SearchContext shadowRootTwo = expandRootElement (nestedShadowHost);

Finally, it is time now to locate the actual element for getting the text – “nested text”.

The following line of code will help us in locating text:

1

2

shadowRootTwo.findElement (By.cssSelector ("#nested_shadow_content > div"))

.getText ();

Demonstration

In this section of this article on Shadow DOM in Selenium, let’s quickly write a test and check that the locators we found in the previous steps are providing us with the required text, and we can run assertions on the code we wrote to verify what we are expecting from the code is working.

(Video) What is Shadow DOM? | How to identify shadow root elements using Selenium 4 | GetShadowRoot method

1

2

3

4

5

6

7

8

9

10

@Test

public void testShadowDomWatir () {

getDriver ().get ("http://watir.com/examples/shadow_dom.html");

HomePage homePage = new HomePage ();

// assertEquals (homePage.getSomeText(), "some text");

assertEquals (homePage.getShadowDomText (), "some text");

assertEquals (homePage.getNestedShadowText (),"nested text");

assertEquals (homePage.getNestedText (), "nested text");

assertEquals (homePage.getNestedTextUsingJSExecutor (), "nested text");

}

This is just a simple test to assert the texts are displayed as correctly as expected. We would be checking that using the assertEquals() assertion in TestNG.

In actual value, we would provide the method we just wrote to get the text from the page, and in the expected value, we would pass the text “some text” or “nested text” depending on the assertions we would be doing.

There are 4 assertEquals statements provided in the test.

  • Checking the Shadow DOM element using the getShadowRoot() method.
  • How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (14)

  • Checking the nested Shadow DOM element using the getShadowRoot() method.
  • How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (15)

  • Checking the nested Shadow DOM element using the getShadowRoot() method and writing fluently.
  • How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (16)

  • Checking the nested Shadow DOM element using JavaScriptExecutor.
  • How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (17)

Execution

There are two ways to run the tests for automating Shadow DOM in Selenium:

  • From the IDE using TestNG.
  • From the CLI using Maven.

Automating Shadow DOM in Selenium WebDriver using TestNG

TestNG is used as a test runner. Hence testng.xml has been created using which we will run the tests by right-clicking on the file and selecting the option Run ‘…\testng.xml’. But before running the tests, we need to add the LambdaTest username and access Key in the Run Configurations since we are reading the username and accesskey from System Property.

LambdaTest offers cross browser testing on an online browser farm of over 3000 real browsers and operating systems to help you run Java tests both locally and/or in the cloud. You can accelerate your Selenium testing with Java and reduce test execution time by multiple folds by running parallel tests on multiple browsers and OS configurations.

Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorial around automated browser testing, Cypress E2E testing, Mobile App Testing, and more.

  • Add Values in the Run Configuration as mentioned below:
    • Dusername = < LambdaTest username >
    • DaccessKey = < LambdaTest access key >

Here is the screenshot of the test run locally for Shadow DOM in Selenium using Intellij IDE.

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (18)

Automating Shadow DOM in Selenium WebDriver using Maven

To run the tests using Maven, the following steps need to be run to automate Shadow DOM in Selenium:

  1. Open command Prompt/Terminal.
  2. Navigate to the root folder of the project.
  3. Type the command: mvn clean install -Dusername=< LambdaTest username > -DaccessKey=< LambdaTest accessKey >.

Following is the screenshot from IntelliJ, which shows the execution status of the tests using Maven:

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (19)

Once the tests are run successfully, we can check out the LambdaTest Dashboard and view all the video recordings, screenshots, device logs, and step-by-step granular details of the test run. Check out the screenshots below, which will give you a fair idea of the dashboard for automated app tests.

LambdaTest Dashboard

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (20)

The following screenshots show the details of the build and the tests that were run for automating Shadow DOM in Selenium. Again, the test name, browser name, browser version, OS name, respective OS version, and screen resolution are all correctly visible for each test.

It also has the video of the test that was run, giving a better idea about how tests were run on the device.

LambdaTest Build Details

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (21)

This screen shows all the metrics in detail, which are very helpful from the tester’s point of view to check what test was run on which browser and accordingly view the logs for automating Shadow DOM in Selenium.

LambdaTest Build Details – with logs

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (22)

You can access the latest test results, their status, and the overall number of tests passed or failed in the LambdaTest Analytics Dashboard. In addition, you may see snapshots of recently executed test runs in the Test Overview section.

How To Automate Shadow DOM In Selenium WebDriver | LambdaTest (23)

If you’re a Selenium tester or developer, the LambdaTest Selenium Java 101 certification can help you advance your Selenium with Java skills.

Conclusion

In this blog on automating Shadow DOM in Selenium, we discussed how to find Shadow DOM elements and automate them using the getShadowRoot() method introduced in the Selenium WebDriver’s 4.0.0 and above version.

We also discussed locating and automating the Shadow DOM elements using JavaScriptExecutor in Selenium WebDriver and running the tests on LambdaTest’s Platform, which shows granular details of the tests that were run with Selenium WebDriver logs.

I hope this blog on Shadow DOM in Selenium gives you a fair idea about automating Shadow DOM elements using Selenium WebDriver.

Happy Testing!

Frequently Asked Questions (FAQs)

What is the use of shadow DOM?

When you use Shadow DOM, you can place your component code into its custom element. This allows you to keep your markup free from any additional classes or IDs that might clash with anything on the page.

What is shadow DOM and how is it different from DOM?

Shadow DOM is a way to encapsulate the styles and JavaScript of an element tree within a document without affecting the rest of the page. It’s a way to create an isolated world that can’t be interfered with by other parts of the page. The Shadow DOM is different from the Document Object Model (DOM).

The DOM is the collection of elements in a document and their properties, like id, class, and style. You can think of a shadow DOM as something similar to a DOM, but inside it are hidden or encapsulated things that you can’t see unless you look closely

Faisal Khatri

Faisal is a Software Testing Professional having 14+ years of experience in automation as well as manual testing. He is a QA, freelancer, blogger and open source contributor.

(Video) Selenium Locators - Part 4 | - Locating Elements in Shadow DOM

He loves learning new tools and technologies and sharing his experience by writing blogs.

See author's profile

Videos

1. How to handle #ShadowDom elements in Selenium || What is ShadowDom & ShadowRoot in DOM
(Naveen AutomationLabs)
2. Selenium Tutorial for Beginners 9 - Selenium Testing with Shadow DOM
(ProgrammingKnowledge)
3. How to automate shadow dom in Selenium, Playwright and Cypress | Shadow Root | Multiple Shadow DOM
(SelectorsHub)
4. How to handle shadow-root(user agent) in selenium | Automate user agent shadow dom
(SelectorsHub)
5. Handle shadowDOM elements using selenium java
(qavbox)
6. How to automate closed shadow dom which is inside open shadow dom | shadow root | selenium
(SelectorsHub)
Top Articles
Latest Posts
Article information

Author: Delena Feil

Last Updated: 03/06/2023

Views: 5550

Rating: 4.4 / 5 (45 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.