Home > front end >  Exception when accessing shadow root DOM on webpage with Selenium and Chrome Webdriver
Exception when accessing shadow root DOM on webpage with Selenium and Chrome Webdriver

Time:11-25

I'm trying to access the shadow root DOM on a web page using Java with Selenium and Chrome Webdriver. Up until today, I've been doing this successfully using the following line

WebElement ele = (WebElement) ((JavascriptExecutor)driver).executeScript("return arguments[0].shadowRoot", element);

However, after Google Chrome updated itself today, I was forced to update Chrome Webdriver, and now I get the following exception:

Error: class com.google.common.collect.Maps$TransformedEntriesMap cannot be cast to class org.openqa.selenium.WebElement (com.google.common.collect.Maps$TransformedEntriesMap and org.openqa.selenium.WebElement are in unnamed module of loader 'app')

My configuration is Google Chrome 96.0.4664.45, Selenium 4.0, Eclipse 4.21.0/JDK jdk-15.0.2

I can avoid an exception by doing this:

List <WebElement> eleList = (List <WebElement>) ((JavascriptExecutor)driver)
                .executeScript("return arguments[0].shadowRoot.children", element);
                    return eleList.get(0);

but it doesn't open up the shadow root element for me. Any suggestions?

CodePudding user response:

Here's my own solution in case it helps someone:

  1. download automation-0.1.3.jar from maven and add to project. see https://github.com/sukgu/shadow-automation-selenium/wiki

  2. new code:

              Shadow shadow = new Shadow(driver);
    
              WebElement myWebElement=shadow.findElement("div.content");
    

CodePudding user response:

Instead of "children" use "childNodes".

Examples: https://developer.mozilla.org/en-US/docs/Web/API/Element/shadowRoot#examples

List <WebElement> eleList = (List <WebElement>) ((JavascriptExecutor)driver)
            .executeScript("return arguments[0].shadowRoot.childNodes", element);
                return eleList.get(0);
  • Related