Skip to content

Commit 8ed78cf

Browse files
committed
Support pruning by xpath in xml-prune scriptlet
Related issue: - uBlockOrigin/uAssets#18244
1 parent 6327345 commit 8ed78cf

1 file changed

Lines changed: 29 additions & 1 deletion

File tree

assets/resources/scriptlets.js

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1998,7 +1998,10 @@ builtinScriptlets.push({
19981998
name: 'xml-prune.js',
19991999
fn: xmlPrune,
20002000
dependencies: [
2001+
'get-extra-args.fn',
20012002
'pattern-to-regex.fn',
2003+
'safe-self.fn',
2004+
'should-log.fn',
20022005
],
20032006
});
20042007
function xmlPrune(
@@ -2009,15 +2012,40 @@ function xmlPrune(
20092012
if ( typeof selector !== 'string' ) { return; }
20102013
if ( selector === '' ) { return; }
20112014
const reUrl = patternToRegex(urlPattern);
2015+
const extraArgs = getExtraArgs(Array.from(arguments), 3);
2016+
const log = shouldLog(extraArgs);
2017+
const queryAll = (xmlDoc, selector) => {
2018+
const isXpath = /^xpath\(.+\)$/.test(selector);
2019+
if ( isXpath === false ) {
2020+
return Array.from(xmlDoc.querySelectorAll(selector));
2021+
}
2022+
const xpr = xmlDoc.evaluate(
2023+
selector.slice(6, -1),
2024+
xmlDoc,
2025+
null,
2026+
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
2027+
null
2028+
);
2029+
const out = [];
2030+
for ( let i = 0; i < xpr.snapshotLength; i++ ) {
2031+
const node = xpr.snapshotItem(i);
2032+
if ( node.nodeType !== 1 ) { continue; }
2033+
out.push(node);
2034+
}
2035+
return out;
2036+
};
20122037
const pruneFromDoc = xmlDoc => {
20132038
try {
20142039
if ( selectorCheck !== '' && xmlDoc.querySelector(selectorCheck) === null ) {
20152040
return xmlDoc;
20162041
}
2017-
const elems = xmlDoc.querySelectorAll(selector);
2042+
const elems = queryAll(xmlDoc, selector);
20182043
if ( elems.length !== 0 ) {
20192044
for ( const elem of elems ) {
20202045
elem.remove();
2046+
if ( log ) {
2047+
safeSelf().uboLog(`xmlPrune: ${elem.nodeName} removed`);
2048+
}
20212049
}
20222050
}
20232051
} catch(ex) {

0 commit comments

Comments
 (0)