-1

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);
}

 
JeffC
  • 22,180
  • 5
  • 32
  • 55
MyungHee
  • 23
  • 7
  • Screenshots of the UI are great, screenshots of code or HTML are not. Please read why [a screenshot of code/HTML is a bad idea](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors). Paste the code/HTML as text and properly format it instead. – JeffC Apr 04 '23 at 16:44

1 Answers1

0

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.

JeffC
  • 22,180
  • 5
  • 32
  • 55
  • with the code you provided, i get `org.openqa.selenium.NoSuchShadowRootException: no such shadow root` – MyungHee Apr 04 '23 at 17:12
  • I'm just using the locators you provided. If you want updated locators, edit your question and post the relevant HTML as text, properly formatted. – JeffC Apr 04 '23 at 17:47