Test on 3000+ browsers

Get 100 minutes of automation test minutes FREE!!

LT

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

Kane
Book A Demo

How To Automate Shadow DOM In Selenium WebDriver

Faisal Khatri

Posted On: September 26, 2022

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?

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.

What-is-Shadow-DOM

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

Figure 1

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”).

screenshot of the Homepage class

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

screenshot of the tests

Error on Running the tests shows NoSuchElementException

Error on Running the tests shows NoSuchElementException

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.

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:

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

Github Button

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.

move on to the code now

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

FileName – HomePage class

Code Walkthrough

getShadowDomText() method:

getShadowDomText() method

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

first element that we would be locating

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.

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:

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.

locator of nested text

getNestedShadowText() method:

getNestedShadowText

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

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:

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:

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:

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.

getShadowRoot

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.

getNestedTextUsingJSExecutor() method:

getNestedTextUsingJSExecutor() method

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.

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

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:

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.

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.
  • getShadowRoot

  • Checking the nested Shadow DOM element using the getShadowRoot() method.
  • getShadowRoot

  • Checking the nested Shadow DOM element using the getShadowRoot() method and writing fluently.
  • getShadowRoot

  • Checking the nested Shadow DOM element using JavaScriptExecutor.
  • JavaScriptExecutor

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.

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

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:

screenshot from IntelliJ

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

LambdaTest Dashboard

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

LambdaTest Build Details

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

LambdaTest Build Details - with logs

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.

LambdaTest Analytics Dashboard

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

https://www.lambdatest.com/certifications/selenium-java-101

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

Author

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. He loves learning new tools and technologies and sharing his experience by writing blogs.

Blogs: 9

linkedintwitter