Skip to content

Commit

Permalink
Improve trusted-replace-[fetch|xhr]-response scriptlets
Browse files Browse the repository at this point in the history
  • Loading branch information
gorhill committed Jun 13, 2024
1 parent 441cf7c commit 9072772
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions assets/resources/scriptlets.js
Original file line number Diff line number Diff line change
Expand Up @@ -1332,6 +1332,8 @@ function replaceFetchResponseFn(
if ( pattern === '*' ) { pattern = '.*'; }
const rePattern = safe.patternToRegex(pattern);
const propNeedles = parsePropertiesToMatch(propsToMatch, 'url');
const extraArgs = safe.getExtraArgs(Array.from(arguments), 4);
const reIncludes = extraArgs.includes ? safe.patternToRegex(extraArgs.includes) : null;
self.fetch = new Proxy(self.fetch, {
apply: function(target, thisArg, args) {
const fetchPromise = Reflect.apply(target, thisArg, args);
Expand Down Expand Up @@ -1361,6 +1363,9 @@ function replaceFetchResponseFn(
return fetchPromise.then(responseBefore => {
const response = responseBefore.clone();
return response.text().then(textBefore => {
if ( reIncludes && reIncludes.test(textBefore) === false ) {
return responseBefore;
}
const textAfter = textBefore.replace(rePattern, replacement);
const outcome = textAfter !== textBefore ? 'match' : 'nomatch';
if ( outcome === 'nomatch' ) { return responseBefore; }
Expand Down Expand Up @@ -4365,6 +4370,8 @@ function trustedReplaceXhrResponse(
if ( pattern === '*' ) { pattern = '.*'; }
const rePattern = safe.patternToRegex(pattern);
const propNeedles = parsePropertiesToMatch(propsToMatch, 'url');
const extraArgs = safe.getExtraArgs(Array.from(arguments), 3);
const reIncludes = extraArgs.includes ? safe.patternToRegex(extraArgs.includes) : null;
self.XMLHttpRequest = class extends self.XMLHttpRequest {
open(method, url, ...args) {
const outerXhr = this;
Expand Down Expand Up @@ -4402,6 +4409,9 @@ function trustedReplaceXhrResponse(
if ( typeof innerResponse !== 'string' ) {
return (xhrDetails.response = innerResponse);
}
if ( reIncludes && reIncludes.test(innerResponse) === false ) {
return (xhrDetails.response = innerResponse);
}
const textBefore = innerResponse;
const textAfter = textBefore.replace(rePattern, replacement);
if ( textAfter !== textBefore ) {
Expand Down

0 comments on commit 9072772

Please sign in to comment.