How to automate Shadow DOM & Nested Shadow DOM elements in selenium?
We can’t access the shadow dom elements like other web elements.
Like driver.findElement(..) can’t be used directly to handle shadow dom elements.
- Here first we need to locate the host element of shadow root then
- Get the access of shadow dom using JS through host element, it can be called as last element.
- Now shadow dom elements can be accessed using this last element.
Sample script-
//This Element is inside single shadow DOM.
String cssSelectorForHost1 = “book-app[apptitle=’BOOKS’]”;
Thread.sleep(1000);
WebElement shadowDomHostElement = driver.findElement(By.cssSelector(“book-app[apptitle=’BOOKS’]”));
WebElement last = (WebElement) ((JavascriptExecutor) driver).executeScript(“return arguments[0].shadowRoot”, shadowDomHostElement);
Thread.sleep(1000);
last.findElement(By.cssSelector(“#input”));
Similarly if an element is inside multiple shadow doms then we will have to traverse one by one all the shadow dom and then access element.
It is very challenging and time wasting task to verify and generate selectors for shadow DOM using browser DevTools.
SelectorsHub made it very easy and one click task. Just inspect the element and SelectorsHub will give the selectors for elements, for all shadow root host and the complete script which can be directly used in automation script.
SelectorsHub is a FREE browser extension.
Download link — https://selectorshub.com/
To understand more about it in details with practical scenario, please checkout this video tutorial-