To access Shadow DOM elements in Selenium 4 with Chrome v96+ use the new
What happened in v96 is that Chrome has made its shadow root values compliant with the updated W3C WebDriver specification, which now includes definitions getting an element’s shadow root and locating elements in a shadow root. Microsoft Edge will support this functionality in v96, and we can expect Firefox to add support soon. Additionally, the Selenium team is working to get support added to WebKit, so eventually we’ll see this in Safari.
This code works for Chrome before v96, Edge before v96 and Safari.
The issue is that Chrome v96 breaks this code because the script getting executed is no longer
returning a value that can be parsed by the
WebElement interface. The cast error looks like this:
The fix for this in Selenium 4 is to change the cast from the
WebElement interface to the
ShadowRoot class itself is kept as package-private because we want people to code against the
SearchContext API directly. This change is backwards compatible with what you’ve been doing, since
Note that not all the Selenium bindings considered this use case, so getting a shadow root object instance from a script execution might not be able to work in non-Java languages until Selenium 4.1.
So far, I haven’t mentioned Firefox— that’s because it is special. Until Firefox implements
W3C-compliant shadow root support, you have to get the shadow DOM elements from the executed script directly
children property, then loop through the elements to find the one you want to work with:
or answer one of these questions in the comments or on Twitter: