Home > Blockchain >  isDisplayed, isEnabled, isSelected method available in Java script for shodow dom elements in seleni
isDisplayed, isEnabled, isSelected method available in Java script for shodow dom elements in seleni

Time:12-01

Selenium Version: 4.0.0

Is there a way to implement isDisplayed, isEnabled, isSelected Methods in Selenium using Java script for shadow dom elements?

I tried these similar steps below but apparently not worked. Any guidance please?

Code:

   public void isEnabledUsingJavaScript() {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    Boolean test= (Boolean) js.executeScript("document.querySelector("foo >boo").shadowRoot.querySelector("foo>boo>span").enable()");
    System.out.println(test);
}

Note: Since it is a showdow dom, the usual XPATH or CSS selectors cannot be applied.

Error:-

org.openqa.selenium.JavascriptException: javascript error: document.querySelector(...).shadowRoot.querySelector(...).enable is not a function

While I understand the error, not sure which appropriate method exists in java script to use in these kind of scenarios.

CodePudding user response:

You need to typecast the variable returned to webElement, Then you will be able to perform all operation which can be done in a webElement.

For your reference, below is a website (https://www.studydrive.net), where Accept cookie button appears under a shadow root, which with the help of java script executor, can be fetched from page and type casted to web element.

driver = new ChromeDriver();
driver.get("https://www.studydrive.net/") ;
driver.manage().window().maximize();
JavascriptExecutor js = (JavascriptExecutor) driver;
Thread.sleep(30);
WebElement element = (WebElement) js.executeScript("return document.querySelector('#usercentrics-root').shadowRoot.querySelector('#uc-center-container > div.sc-jcVcSv.gBDztr > div > div.sc-giImIA.jqkmtR > div > button.sc-gsTEea.ffHglG')");

if(element.isDisplayed()) {
System.out.println("element is displayed");
element.click();
System.out.println("element is clicked");
} else {
 System.out.println("element is not visible");
}

Output:

element is displayed
element is clicked
  • Related