Skip to content

Commit 32a4d64

Browse files
committed
Improve trusted-click-element scriptlet
Add support for xpath expressions: if a selector starts with `xpath:`, the selector will instead be used as an xpath expression to find the matching elements. Related discussion: uBlockOrigin/uAssets#33142
1 parent bc5fa9f commit 32a4d64

1 file changed

Lines changed: 13 additions & 2 deletions

File tree

src/js/resources/scriptlets.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1888,12 +1888,23 @@ function trustedClickElement(
18881888
return elem.shadowRoot;
18891889
};
18901890

1891+
const queryOrEvaluateSelector = (selector, context) => {
1892+
if ( selector.startsWith('xpath:') === false ) {
1893+
return context.querySelector(selector);
1894+
}
1895+
const result = document.evaluate(selector.slice(6), context, null, 9, null);
1896+
if ( result.resultType !== 9 ) { return null; }
1897+
const elem = result.singleNodeValue;
1898+
if ( elem?.nodeType !== 1 ) { return null; }
1899+
return elem;
1900+
}
1901+
18911902
const querySelectorEx = (selector, context = document) => {
18921903
const pos = selector.indexOf(' >>> ');
1893-
if ( pos === -1 ) { return context.querySelector(selector); }
1904+
if ( pos === -1 ) { return queryOrEvaluateSelector(selector, context); }
18941905
const outside = selector.slice(0, pos).trim();
18951906
const inside = selector.slice(pos + 5).trim();
1896-
const elem = context.querySelector(outside);
1907+
const elem = queryOrEvaluateSelector(outside, context);
18971908
if ( elem === null ) { return null; }
18981909
const shadowRoot = getShadowRoot(elem);
18991910
return shadowRoot && querySelectorEx(inside, shadowRoot);

0 commit comments

Comments
 (0)