Add `trusted-replace-outbound-text` scriptlet

Related issue:
https://github.com/uBlockOrigin/uBlock-issues/issues/3157

Paremeters:
- `pattern`: a string or regex to match in the outbound text. If
  not provided or empty, the scriptlet will only log the outbound
  text without modifying it.
- `replacement`: the replacement string for the matched part.
This commit is contained in:
Raymond Hill 2024-04-01 11:27:19 -04:00
parent 6876fa46cc
commit 21e1ee30ee
No known key found for this signature in database
GPG Key ID: 25E1490B761470C2
1 changed files with 35 additions and 0 deletions

View File

@ -4704,3 +4704,38 @@ function trustedReplaceArgument(
}
/******************************************************************************/
builtinScriptlets.push({
name: 'trusted-replace-outbound-text.js',
requiresTrust: true,
fn: trustedReplaceOutboundText,
dependencies: [
'proxy-apply.fn',
'safe-self.fn',
],
});
function trustedReplaceOutboundText(
propChain = '',
pattern = '',
replacement = ''
) {
if ( propChain === '' ) { return; }
const safe = safeSelf();
const logPrefix = safe.makeLogPrefix('trusted-replace-outbound-text', propChain, pattern, replacement);
const rePattern = safe.patternToRegex(pattern);
const reflector = proxyApplyFn(propChain, function(...args) {
const textBefore = reflector(...args);
const textAfter = pattern !== ''
? textBefore.replace(rePattern, replacement)
: textBefore;
if ( textAfter !== textBefore ) {
safe.uboLog(logPrefix, 'Matched and replaced');
}
if ( safe.logLevel > 1 || pattern === '' ) {
safe.uboLog(logPrefix, 'Outbound text:\n', textAfter);
}
return textAfter;
});
}
/******************************************************************************/