CodexBloom - Programming Q&A Platform

Selenium WebDriver scenarios to interact with Shadow DOM elements in Angular 14 application

πŸ‘€ Views: 548 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-25
selenium-webdriver angular shadow-dom Java

Could someone explain I'm working on a personal project and Does anyone know how to Quick question that's been bugging me - I'm having trouble interacting with elements that are inside a Shadow DOM in my Angular 14 application using Selenium WebDriver with Java... I've tried using JavaScriptExecutor to access the Shadow DOM elements but I'm getting a `NoSuchElementException` when I try to interact with them. Here’s what I’ve attempted: First, I tried to locate the Shadow DOM host element and then access the shadow root: ```java WebDriver driver = new ChromeDriver(); driver.get("http://localhost:4200"); WebElement shadowHost = driver.findElement(By.cssSelector("#shadow-host")); JavascriptExecutor js = (JavascriptExecutor) driver; WebElement shadowRoot = (WebElement) js.executeScript("return arguments[0].shadowRoot", shadowHost); ``` After that, I attempted to find a button inside the shadow DOM like this: ```java WebElement button = shadowRoot.findElement(By.cssSelector("button#submit")); button.click(); ``` However, this results in a `NoSuchElementException`, stating that the button want to be found. I've confirmed that the button exists in the Shadow DOM by inspecting it in the Chrome Developer Tools. I've also attempted to directly execute JavaScript to click the button: ```java js.executeScript("arguments[0].click();", button); ``` This still does not work, and I get no errors, but the button doesn't respond as expected. I've ensured my ChromeDriver version matches my Chrome browser version (Chrome 115) and that the necessary dependencies for Selenium WebDriver are up to date. Can anyone provide insight into how to properly interact with elements within a Shadow DOM using Selenium? Any best practices or examples would be greatly appreciated! Any ideas what could be causing this? This is part of a larger CLI tool I'm building. What am I doing wrong? I've been using Java for about a year now. Could this be a known issue?