Looking for the best way to convert an Object to WebElement or SearchContext using JavaScript?
In Java, casting as `(WebElement)` or `(SearchContext)` works fine. However, attempting the same in JavaScript with `as Webelement` or `as SearchContext` results in an error.
Caused by: java.lang.ClassCastException: com.google.common.collect.Maps$TransformedEntriesMap cannot be cast to org.openqa.selenium.SearchContext
This issue also arises with Shadow Root.
Java Code:
webElemHost = browser.findElement(By.xpath("//tagHere[@id='idHere']"));
strCSSSelector = "#idHere";
JavascriptExecutor js = (JavascriptExecutor) browser;
SearchContext shadowRoot = (SearchContext) js.executeScript("return arguments[0].shadowRoot", webElemHost);
WebElement shadowContent = shadowRoot.findElement(By.cssSelector(strCSSSelector));
JavaScript Code (Not Working):
webElemHost = browser.findElement(By.xpath("//tagHere[@id='idHere']"));
strCSSSelector = "#idHere";
var JavascriptExecutor js = browser as JavascriptExecutor;
var SearchContext shadowRoot = js.executeScript("return arguments[0].shadowRoot", webElemHost) as SearchContext; <== ERROR HERE
var WebElement shadowContent = shadowRoot.findElement(By.cssSelector(strCSSSelector));
Please note that using the getShadowRoot function of findElement is not possible due to limitations in Selenium Version (limited to v3).