Search:
Thread.sleep(2000);
SearchContext shadowHostEls =
(SearchContext) (js.executeScript("return document.querySelector(\""+my-open-component+"\").shadowRoot"));
shadowHostEls.findElement(By.cssSelector("input")).sendKeys("qavboxOpen");
Js.executeScript(….).shadowRoot returns the SearchContext which is parent to the WebElement, so we can use the SearchContext object/variable “shadowHostEls” to fetch all the root elements of the shadowDOM and perform actions.
This above code will work if you are using Selenium 3 or 4.
Note – If you are using Chrome > 96 version and using WebElement as return type of JS.executeScript, then you will get an exception as “o
rg.openqa.selenium.remote.ShadowRoot
cannot be cast to org.openqa.selenium.WebElement java.lang.
ClassCastException
: org.openqa.selenium.remote.
ShadowRoot
cannot be cast to org.openqa.selenium.
WebElement
“
So please use
SearchContext
instead of
WebElement
Thread.sleep(2000);
SearchContext shadowHostEls = driver.findElement(By.cssSelector("my-open-component")).getShadowRoot();
shadowHostEls.findElement(By.cssSelector("input")).sendKeys("qavboxOpen");
Note – this above method will work only if you have an OPEN shadowDOM.
connectedCallback() {
this._root.innerHTML = '<div>Close shadow with ref=_root</div><input type="text"></input><br>'
this._root
is the reference to the closed shadowDOM element and we can automate the elements inside this shadowRoot.
driver = new ChromeDriver();
driver.get("https://qavbox.github.io/demo/shadowDOM/");
js = (JavascriptExecutor) driver;
Thread.sleep(2000);
SearchContext shadowHostEls =
(SearchContext) (js.executeScript("return document.querySelector(\""+my-close-component+"\")._root"));
shadowHostEls.findElement(By.cssSelector("input")).sendKeys("qavboxOpen");
Observe the 7th line of above code, we used ._root instead of shadowRoot to identify the closed shadowRoot with reference.
hope this helps!