Skip to content

Instantly share code, notes, and snippets.

@rjvdw rjvdw/ByShadow.kt
Last active Dec 11, 2018

Embed
What would you like to do?
Match a CSS selector within all shadow roots
import org.openqa.selenium.By
import org.openqa.selenium.JavascriptExecutor
import org.openqa.selenium.SearchContext
import org.openqa.selenium.WebElement
class ByShadow(vararg selectors: String) : By() {
private val args = "['" + selectors.joinToString("','") + "']"
override fun findElements(ctx: SearchContext): List<WebElement> {
val result = (ctx as JavascriptExecutor).executeScript("""
return ((selectors) => {
'use strict';
function deepSelect(node, selector) {
return Array.from(node.querySelectorAll(selector))
.concat(
Array.from(node.querySelectorAll('*'))
.filter(node => node.shadowRoot)
.flatMap(node => deepSelect(node.shadowRoot, selector))
);
}
return selectors.reduce(
(nodes, selector) => nodes
.concat(nodes
.filter(node => node.shadowRoot)
.map(node => node.shadowRoot))
.flatMap(node => deepSelect(node, selector)),
[document],
);
})($args)
""")
if (result is List<*> && result.all { el -> el is WebElement }) {
@Suppress("UNCHECKED_CAST")
return result as? List<WebElement> ?: emptyList()
}
return emptyList()
}
}
function deepQuery(node, query) {
'use strict'
return Array.from(node.querySelectorAll(query))
.concat(
Array.from(node.querySelectorAll('*'))
.filter(node => node.shadowRoot)
.flatMap(node => deepQuery(node.shadowRoot, query))
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.