Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(adblocker): inject scriplets with browser.contentScripts on Firefox #2074

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 79 additions & 4 deletions src/background/adblocker.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ export async function reloadMainEngine() {
await engines.create(engines.MAIN_ENGINE);
console.info('[adblocker] Main engine reloaded with no filters');
}
if (__PLATFORM__ === 'firefox') {
contentScripts.unregisterAll();
}
}

let updating = false;
Expand Down Expand Up @@ -167,7 +170,49 @@ export const setup = asyncSetup([
* Cosmetics injection
*/

async function injectScriptlets(scripts, tabId, frameId) {
const contentScripts = (() => {
smalluban marked this conversation as resolved.
Show resolved Hide resolved
const map = new Map();
return {
async register(hostname, code) {
this.unregister(hostname);
try {
const contentScript = await browser.contentScripts.register({
js: [
{
code,
},
],
allFrames: true,
matches: [`https://*.${hostname}/*`, `http://*.${hostname}/*`],
matchAboutBlank: true,
matchOriginAsFallback: true,
runAt: 'document_start',
});
map.set(hostname, contentScript);
} catch (e) {
console.warn(e);
this.unregister(hostname);
}
},
isRegistered(hostname) {
return map.has(hostname);
},
unregister(hostname) {
const contentScript = map.get(hostname);
if (contentScript) {
contentScript.unregister();
map.delete(hostname);
}
},
unregisterAll() {
for (const hostname of map.keys()) {
this.unregister(hostname);
}
},
};
})();

async function injectScriptlets(scripts, tabId, frameId, hostname) {
// Dynamically injected scriptlets can be difficult to find later in
// the debugger. Console logs simplifies setting up breakpoints if needed.
if (debugMode) {
Expand Down Expand Up @@ -196,6 +241,21 @@ async function injectScriptlets(scripts, tabId, frameId) {
script.remove();
}

if (__PLATFORM__ === 'firefox') {
if (scripts.length === 0) {
contentScripts.unregister(hostname);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if this part of the code is necessary or how it should be best handled.
When the engine updates, it should automatically clear the content scripts (contentScripts.unregisterAll). There might be potential for race conditions, but in principle, it should eventually take care of unregistering.

Is the code here intended especially for pause (which won't trigger an engine reload)? If so, would be good to leave a comment explaining this.

} else if (!contentScripts.isRegistered(hostname)) {
await contentScripts.register(
hostname,
`(${scriptletInjector.toString()})("${encodeURIComponent(scriptlets)}")`,
);
} else {
// do nothing if already registered
}
return;
}
if (scripts.length === 0) return;

chrome.scripting.executeScript(
{
injectImmediately: true,
Expand Down Expand Up @@ -236,6 +296,9 @@ function injectStyles(styles, tabId, frameId) {
}

async function injectCosmetics(details, config) {
const isBootstrap = config.bootstrap;
const scriptletsOnly = Boolean(config.scriptletsOnly);

try {
setup.pending && (await setup.pending);
} catch (e) {
Expand All @@ -249,6 +312,8 @@ async function injectCosmetics(details, config) {
const domain = parsed.domain || '';
const hostname = parsed.hostname || '';

if (scriptletsOnly && contentScripts.isRegistered(hostname)) return;

if (isPaused(options, hostname)) return;

const tabHostname = tabStats.get(tabId)?.hostname;
Expand All @@ -257,7 +322,6 @@ async function injectCosmetics(details, config) {
}

const engine = engines.get(engines.MAIN_ENGINE);
const isBootstrap = config.bootstrap;

{
const cosmetics = engine.getCosmeticsFilters({
Expand All @@ -279,8 +343,12 @@ async function injectCosmetics(details, config) {
getRulesFromDOM: !isBootstrap,
});

if (isBootstrap && cosmetics.scripts.length > 0) {
injectScriptlets(cosmetics.scripts, tabId, frameId);
if (isBootstrap) {
injectScriptlets(cosmetics.scripts, tabId, frameId, hostname);
}

if (scriptletsOnly) {
return;
}

if (cosmetics.styles) {
Expand Down Expand Up @@ -365,6 +433,13 @@ function isTrusted(request, type) {
}

if (__PLATFORM__ === 'firefox') {
chrome.webNavigation.onBeforeNavigate.addListener(
(details) => {
injectCosmetics(details, { bootstrap: true, scriptletsOnly: true });
},
{ url: [{ urlPrefix: 'http://' }, { urlPrefix: 'https://' }] },
);

function isExtensionRequest(details) {
return (
(details.tabId === -1 && details.url.startsWith('moz-extension://')) ||
Expand Down
Loading