A simplified version of @Dilip Meghwal's answer:
public static WebElement pierceShadowRoot(String... selectors) {
WebElement element = null;
WebElement shadowRoot = null;
for (String selector : selectors) {
if (element == null) {
element = getDriver().findElement(By.cssSelector(selector));
} else {
shadowRoot = (WebElement) getDriver().executeScript("return arguments[0].shadowRoot", element);
element = (WebElement) shadowRoot.findElement(By.cssSelector(selector));
}
}
return element;
}
As an example, here's how I used it to locate Google Chrome's Clear cache button, where other ways didn't work because of Polymer framework used in Chrome:
WebElement targetElement = pierceShadowRoot("body > settings-ui", "#main", "settings-basic-page",
"#advancedPage > settings-section:nth-child(1) > settings-privacy-page", "settings-clear-browsing-data-dialog",
"#clearBrowsingDataConfirm");