goto100 / xpath

DOM 3 Xpath implemention and helper for node.js
MIT License
222 stars 71 forks source link

Shadow DOM support #142

Open SKYWy opened 1 month ago

SKYWy commented 1 month ago

Hello,

I want to use the library to evaluate xPath in shadow DOMs in HTML, but have a problem when I use it with absolute xPath. Per definition, absolute XPath should look for the target in all of the document, but the document itself does not have access to the content of shadow DOM (which are document-fragment). In my case, the case where we use Shadow DOM as a document and have the absolute xpath only inside it, is enough. Is there a way to achieve it ?

Here is the HTML and Javascript used:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="src/style.css">
  </head>
  <body>
    <h1 id="header"></h1>
    <div id = 'host'>
    </div>

    <script src="src/script.js"></script>
  </body>
</html>
import * as xpath from 'xpath'

const evaluate = (path, node) => {
  const xPath = xpath.parse(path)
  const options = {
    expressionContextNode: node,
    isHtml: true,
    namespaces: '',
    node: node,
  }
  return xPath.evaluate(options)
}

const host = document.querySelector('#host')
const shadowRoot = host.attachShadow({mode: 'open'})
const target = document.createElement('div')
target.id = 'target'
shadowRoot.appendChild(target)

const nestedTarget = document.createElement('div')
nestedTarget.id = 'nestedTarget'
target.appendChild(nestedTarget)

// Log to console
console.log('host', host)
console.log('shadowRoot', shadowRoot.innerHTML)
console.log('Shadow DOM - relative', evaluate('div', shadowRoot).nodes)
console.log('Shadow DOM - relative nested', evaluate('div/div', shadowRoot).nodes)
console.log('Shadow DOM - absolute', evaluate('//div', shadowRoot).nodes)

The screenshot from the devTools

image

And the console

image
SKYWy commented 1 month ago

From what I see, in PathExpr.applyLocationPath, we shouldn't have startNodes = [PathExpr.getRoot(xpc, nodes)] if the node is a document-fragment.

Moreover, in PathExpr.applySteps, it seems that for shadow DOM, the reduce() goes "too far", by that I mean that applyStepToNodes was called once to often.

SKYWy commented 1 month ago

Found the problem, document-fragment were not considered as Node here. #143 fixes it.