From 21e1ee30ee36c1b9a7a3c9f43ac97e52d8e79661 Mon Sep 17 00:00:00 2001 From: Raymond Hill Date: Mon, 1 Apr 2024 11:27:19 -0400 Subject: [PATCH] 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. --- assets/resources/scriptlets.js | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/assets/resources/scriptlets.js b/assets/resources/scriptlets.js index c4ec45164cbf6..91ee1b96f8b7e 100644 --- a/assets/resources/scriptlets.js +++ b/assets/resources/scriptlets.js @@ -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; + }); +} + +/******************************************************************************/