Accessing elements within the #shadow-root (open) while clearing browsing data in Chrome using Selenium can present challenges. To overcome this, we must understand Shadow DOM and Selenium's capabilities.
Shadow DOM allows web developers to encapsulate HTML and style within custom components, creating isolated and independent UI elements. These components, termed "shadow hosts," have their own shadow tree, a hidden DOM fragment.
Selenium doesn't natively support Shadow DOM elements as they lie outside the main DOM tree. To interact with these elements, we must first access their shadow tree.
1. Identifying the Shadow Host:
Locate the shadow host in the main DOM using Selenium's findElement method.
2. Extracting Shadow Root:
Use our custom method getShadowRoot to access the shadow root associated with the shadow host.
3. Navigating Shadow Tree:
Traverse the shadow tree by using our getShadowElement method, passing in the shadow root and CSS selector of the target element.
Using our custom methods, we can navigate the multi-level Shadow DOM to access and click the Clear Browsing Data button:
WebElement shadowHostL1 = driver.findElement(By.cssSelector("settings-ui")); WebElement shadowElementL1 = getShadowElement(driver, shadowHostL1, "settings-main"); WebElement shadowElementL2 = getShadowElement(driver, shadowElementL1, "settings-basic-page"); WebElement shadowElementL3 = getShadowElement(driver, shadowElementL2, "settings-section > settings-privacy-page"); WebElement shadowElementL4 = getShadowElement(driver, shadowElementL3, "settings-clear-browsing-data-dialog"); WebElement shadowElementL5 = getShadowElement(driver, shadowElementL4, "#clearBrowsingDataDialog"); WebElement clearData = shadowElementL5.findElement(By.cssSelector("#clearBrowsingDataConfirm")); clearData.click();
Alternatively, we can use a single JavaScript call:
WebElement clearData = (WebElement) js.executeScript("return document.querySelector(...[CSS selector to traverse Shadow DOM]...");
The above is the detailed content of How Can Selenium Access and Interact with Elements Hidden within Shadow DOM?. For more information, please follow other related articles on the PHP Chinese website!