Skip to content

Commit

Permalink
Add support for xhr in xml-prune
Browse files Browse the repository at this point in the history
  • Loading branch information
gorhill committed May 27, 2023
1 parent ea15cef commit d3fae27
Showing 1 changed file with 41 additions and 10 deletions.
51 changes: 41 additions & 10 deletions assets/resources/scriptlets.js
Original file line number Diff line number Diff line change
Expand Up @@ -2009,26 +2009,33 @@ function xmlPrune(
if ( typeof selector !== 'string' ) { return; }
if ( selector === '' ) { return; }
const reUrl = patternToRegex(urlPattern);
const pruner = text => {
if ( (/^\s*</.test(text) && />\s*$/.test(text)) === false ) {
return text;
}
const pruneFromDoc = xmlDoc => {
try {
const xmlParser = new DOMParser();
const xmlDoc = xmlParser.parseFromString(text, 'text/xml');
if ( selectorCheck !== '' && xmlDoc.querySelector(selectorCheck) === null ) {
return text;
return xmlDoc;
}
const elems = xmlDoc.querySelectorAll(selector);
if ( elems.length !== 0 ) {
for ( const elem of elems ) {
elem.remove();
}
const serializer = new XMLSerializer();
text = serializer.serializeToString(xmlDoc);
}
} catch(ex) {
}
return xmlDoc;
};
const pruneFromText = text => {
if ( (/^\s*</.test(text) && />\s*$/.test(text)) === false ) {
return text;
}
try {
const xmlParser = new DOMParser();
const xmlDoc = xmlParser.parseFromString(text, 'text/xml');
pruneFromDoc(xmlDoc);
const serializer = new XMLSerializer();
text = serializer.serializeToString(xmlDoc);
} catch(ex) {
}
return text;
};
const urlFromArg = arg => {
Expand All @@ -2044,7 +2051,7 @@ function xmlPrune(
}
return realFetch(...args).then(realResponse =>
realResponse.text().then(text =>
new Response(pruner(text), {
new Response(pruneFromText(text), {
status: realResponse.status,
statusText: realResponse.statusText,
headers: realResponse.headers,
Expand All @@ -2053,6 +2060,30 @@ function xmlPrune(
);
}
});
self.XMLHttpRequest.prototype.open = new Proxy(self.XMLHttpRequest.prototype.open, {
apply: async (target, thisArg, args) => {
if ( reUrl.test(urlFromArg(args[1])) === false ) {
return Reflect.apply(target, thisArg, args);
}
thisArg.addEventListener('readystatechange', function() {
if ( thisArg.readyState !== 4 ) { return; }
const type = thisArg.responseType;
if ( type === 'text' ) {
const textin = thisArg.responseText;
const textout = pruneFromText(textin);
if ( textout === textin ) { return; }
Object.defineProperty(thisArg, 'response', { value: textout });
Object.defineProperty(thisArg, 'responseText', { value: textout });
return;
}
if ( type === 'document' ) {
pruneFromDoc(thisArg.response);
return;
}
});
return Reflect.apply(target, thisArg, args);
}
});
}

/******************************************************************************/
Expand Down

0 comments on commit d3fae27

Please sign in to comment.