Using shadow DOM for Cookies consent and Test it with Selenium Webdriver

An important aspect of web components is encapsulation - the ability to hide and separate markup structure, styling, and behavior from the rest of the code on the page, so different parts don't conflict and the code can be kept clean. The Shadow DOM API is a key part of it, providing a way to attach a hidden, detached DOM to an element. This post covers the basics of using Shadow DOM.


Shadow Document allows a hidden DOM tree to be added to elements in a regular DOM tree - this shadow Document tree begin with a shadow root under which you can attach to any element in the same way as regular DOM.

 

You should know some shadow DOM terminology:

Shadow host: The regular DOM node to which the shadow DOM is attached.
Shadow Tree: The DOM tree inside the shadow DOM.
Shadow Boundary: Where the shadow DOM ends and the regular DOM begins.
Shadow Root: The root node of the shadow tree.


How to automate shadow DOM elements with Selenium webdriver?


You can remove elements from DOM.


 accept_element = self.driver.find_element_by_xpath('//div[@class="cmpwrapper"]')
self.driver.execute_script("""var element = arguments[0];element.parentNode.removeChild(element);""", accept_element)
                
Or if you need working in root then you can use.

 With Selenium webdriver 4 there is now WebElement.getShadowRoot()

driver.findElement(By.id("parentId")).getShadowRoot().findElement(By.cssSelector( "label" )).findElement(By.tagName("input"))


Or this is an old example. Not tested in my apps. I save it only for information here.

JavascriptExecutor jse = (JavascriptExecutor) driver; WebElement search_box = (WebElement) jse.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('downloads-toolbar#toolbar').shadowRoot.querySelector('cr-toolbar#toolbar').shadowRoot.querySelector('cr-toolbar-search-field#search').shadowRoot.querySelector('div#searchTerm input#searchInput')"); String js = "arguments[0].setAttribute('value','pdf')"; ((JavascriptExecutor) driver).executeScript(js, search_box);




Comments