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
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
Post a Comment