From 1bda7e00859d7d3b405e56eaadd21cf409991790 Mon Sep 17 00:00:00 2001 From: Raymond Hill Date: Wed, 7 Dec 2022 13:48:44 -0500 Subject: [PATCH] Code review of reworked generic cosmetic filtering code Related commit: - https://github.com/gorhill/uBlock/commit/26594fb902b1042843ebda1ab3b3aa6304ed3ae9 --- src/js/contentscript.js | 4 +++- src/js/cosmetic-filtering.js | 19 ++++++++++++++----- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/js/contentscript.js b/src/js/contentscript.js index e6c7b8bf8..75971b6c3 100644 --- a/src/js/contentscript.js +++ b/src/js/contentscript.js @@ -1041,7 +1041,7 @@ vAPI.DOMFilterer = class { } }; - const getSurveyResults = hashes => { + const getSurveyResults = (hashes, safeOnly) => { if ( self.vAPI.messaging instanceof Object === false ) { stop(); return; } @@ -1052,6 +1052,7 @@ vAPI.DOMFilterer = class { hostname, hashes, exceptions: domFilterer.exceptions, + safeOnly, }); promise.then(response => { processSurveyResults(response); @@ -1152,6 +1153,7 @@ vAPI.DOMFilterer = class { idFromNode(document.body, hashes); classesFromNode(document.body, hashes); } + getSurveyResults(hashes, true); addPendingList(document.querySelectorAll( '[id]:not(html):not(body),[class]:not(html):not(body)' )); diff --git a/src/js/cosmetic-filtering.js b/src/js/cosmetic-filtering.js index 9461a703a..27724d9a7 100644 --- a/src/js/cosmetic-filtering.js +++ b/src/js/cosmetic-filtering.js @@ -170,13 +170,15 @@ const hashFromStr = (type, s) => { // It's an uncommon case, so it's best to unescape only when needed. const keyFromSelector = selector => { + let key = ''; let matches = rePlainSelector.exec(selector); - if ( matches === null ) { + if ( matches !== null ) { + key = matches[0]; + } else { matches = rePlainSelectorEx.exec(selector); - if ( matches !== null ) { return matches[1] || matches[2]; } - return; + if ( matches === null ) { return; } + key = matches[1] || matches[2]; } - let key = matches[0]; if ( key.includes('\\') === false ) { return key; } matches = rePlainSelectorEscaped.exec(selector); if ( matches === null ) { return; } @@ -744,10 +746,17 @@ FilterContainer.prototype.retrieveGenericSelectors = function(request) { hashes.push(hash); } + if ( request.safeOnly ) { + for ( const selector of selectorsSet ) { + if ( selector !== keyFromSelector(selector) ) { continue; } + selectorsSet.delete(selector); + } + } + // Apply exceptions: it is the responsibility of the caller to provide // the exceptions to be applied. const excepted = []; - if ( Array.isArray(request.exceptions) ) { + if ( selectorsSet.size !== 0 && Array.isArray(request.exceptions) ) { for ( const exception of request.exceptions ) { if ( selectorsSet.delete(exception) ) { excepted.push(exception);