How to interact an Element under Shadow-DOM

 Hello , in this blog I will show you to how to interact with an elements which is under under Shadow DOM / Shadow Root.

In HTML, the Shadow DOM (Document Object Model) is a way to encapsulate the structure, style, and behavior of a web component. It allows a component to have its own isolated DOM tree and styles, separate from the rest of the page. This isolation prevents styles and scripts outside the component from affecting it, and vice versa, providing better modularity and encapsulation in web development.

Lets say in the below Example: chrome://downloads/

The search input field is under shadow DOM in HTML 



Copy JS path



and paste on Console

Now use as an element and test whether it allowed to setAttribute ( ) or not



If the above works then we are good to use that in our script...


import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class DownloadShadowDom {
public static void main(String[] args) {


WebDriver driver = new ChromeDriver();
driver.get("chrome://downloads/");
driver.manage().window().maximize();
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement search_element =
(WebElement) js.executeScript("return document.querySelector('downloads-manager')" + ".shadowRoot.querySelector('downloads-toolbar#toolbar')" + ".shadowRoot.querySelector('cr-toolbar#toolbar')" + ".shadowRoot.querySelector('div#centeredContent > #search')" + ".shadowRoot.querySelector('div#searchTerm > input#searchInput')");
       String text = "arguments[0].setAttribute('value','Testing from the Java Selenium Script...')";
        js.executeScript(text,search_element);
}
}

Comments

Popular posts from this blog

The self healing automation framework - Healenium Updated Dec2023

Heleanium - Web without using Docker