Skip to content

Commit

Permalink
Add elements vararg to prevent-addEventListener scriptlet
Browse files Browse the repository at this point in the history
If present, `elements` vararg must be a valid CSS selector, which will
be used to apply the scriptlet to only elements matching the
selector.

Related issue:
uBlockOrigin/uBlock-issues#3061

Example of usage:

[...]##+js(aeld, click, return"undefined", elements, a.indirect)
  • Loading branch information
gorhill committed Jan 10, 2024
1 parent a9eb963 commit 060f9d6
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions assets/resources/scriptlets.js
Expand Up @@ -1476,6 +1476,23 @@ function addEventListenerDefuser(
const rePattern = safe.patternToRegex(pattern);
const log = shouldLog(extraArgs);
const debug = shouldDebug(extraArgs);
const targetElements = extraArgs.elements || undefined;
const shouldPrevent = (thisArg, type, handler) => {
const matchesInstance = targetElements === undefined ||
Array.from(document.querySelectorAll(targetElements)).includes(thisArg);
if ( matchesInstance === false ) { return false; }
const matchesType = safe.RegExp_test.call(reType, type);
const matchesHandler = safe.RegExp_test.call(rePattern, handler);
const matchesEither = matchesType || matchesHandler;
const matchesBoth = matchesType && matchesHandler;
if ( log === 1 && matchesBoth || log === 2 && matchesEither || log === 3 ) {
safe.uboLog(`addEventListener('${type}', ${handler})`);
}
if ( debug === 1 && matchesBoth || debug === 2 && matchesEither ) {
debugger; // jshint ignore:line
}
return matchesBoth;
};
const trapEddEventListeners = ( ) => {
const eventListenerHandler = {
apply: function(target, thisArg, args) {
Expand All @@ -1487,17 +1504,7 @@ function addEventListenerDefuser(
: String(args[1]);
} catch(ex) {
}
const matchesType = safe.RegExp_test.call(reType, type);
const matchesHandler = safe.RegExp_test.call(rePattern, handler);
const matchesEither = matchesType || matchesHandler;
const matchesBoth = matchesType && matchesHandler;
if ( log === 1 && matchesBoth || log === 2 && matchesEither || log === 3 ) {
safe.uboLog(`addEventListener('${type}', ${handler})`);
}
if ( debug === 1 && matchesBoth || debug === 2 && matchesEither ) {
debugger; // jshint ignore:line
}
if ( matchesBoth ) { return; }
if ( shouldPrevent(thisArg, type, handler) ) { return; }
return Reflect.apply(target, thisArg, args);
},
get(target, prop, receiver) {
Expand Down

0 comments on commit 060f9d6

Please sign in to comment.