0

Service Now has changed to using shadow root like this

<span id='s1'>
  #shadow-root
   <button>Cancel</button>
   <button>Submit</button>
</span>

I can easily get the first span:

 WebElement sele = driver.findElement(By.xpath("//span[@id='s1']"));

And then get the shadow root:

 SearchContext sc = sele.getShadowRoot();

But it will not let you do a

 sc.findElements(By.xpath(".//button'"));

or more preferably

 WebElement cancelButton = sc.findElement(By.xpath(".//button[.='Cancel']"));

You have to find with CS selector

 sc.findElements(By.cssSelector(" button"));

and go through each button to get the text. To make it worse, when I try

 List<WebElement> buttons = sc.findElements(By.cssSelector(" button"));

because it says there is an error with "=" and it expects "<=". No idea why. Have to do a

 for (WebElement wele : sc.findElements(By.cssSelector(" button")) {
   String txt = wele.getText();
   if (txt.equals("Cancel")) ... // whatever you want
 }

So my question is is there someway to convert "sc" to a WebElement? Even maybe someway to get itself? The equivalent of

 sc.findElement(By.xpath("."));

or someway to look for xpath with SearchContext?

Tony
  • 1,127
  • 1
  • 18
  • 29

1 Answers1

0

Looks like this discussion is exactly what you looking for.
There are several answers given there to get the Shadow Root as a WebElement object.

Prophet
  • 32,350
  • 22
  • 54
  • 79
  • That does not work anymore. Someone mentioned you cannot do that with the new Selenium, use javascriptExecutor to cast SearchContext to WebElement – Tony Nov 30 '22 at 09:58
  • Ah, OK. thank you for letting me to know that. BTW this is why I didn't close this question as duplicate since I wasn't sure it working on Selenium 4... – Prophet Nov 30 '22 at 10:01