javaselenium-webdrivershadow-root

java.lang.NullPointerException error when trying to locate a shadow element with Selenium


I'm trying to locate a field to upload a file, but the element is inside a shadow-root

enter image description here

I tried the following code but I get java.lang.NullPointerException on shadowRoot.findElement:

private static WebElement getShadowRoot(WebDriver driver, WebElement shadowHost) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    return (WebElement) js.executeScript("return arguments[0].shadowRoot", shadowHost);
}
    
public void uploadFileWithIncorrectBirthYear() throws TestingException {
    String url = System.getProperty("user.dir")+"\\src\\test\\resources\\files\\customer-upload-old-birth-year.xls";
    WebElement shadowHost = driver.findElement(By.cssSelector("#cphContent_cifCustomerFile_fakeFileInput"));
    SearchContext shadowRoot = getShadowRoot(driver,shadowHost);
    WebElement shadowElement = shadowRoot.findElement(By.cssSelector("#file-upload-button"));
    shadowElement.sendKeys(url);
}

 

Solution

  • With Selenium 4.0+, there is a .getShadowRoot() method that takes care of this for you. You no longer need your own getShadowRoot() method and your code changes to the below.

    public void uploadFileWithIncorrectBirthYear() throws TestingException {
        String url = System.getProperty("user.dir")+"\\src\\test\\resources\\files\\customer-upload-old-birth-year.xls";
        SearchContext shadowRoot = driver.findElement(By.cssSelector("#cphContent_cifCustomerFile_fakeFileInput")).getShadowRoot();
        WebElement shadowElement = shadowRoot.findElement(By.cssSelector("#file-upload-button"));
        shadowElement.sendKeys(url);
    }
    

    Notice that the .getShadowRoot() method returns a SearchContext not a WebElement.