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 2 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
104 changes: 83 additions & 21 deletions src/background/adblocker.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export async function reloadMainEngine() {
await engines.create(engines.MAIN_ENGINE);
console.info('[adblocker] Main engine reloaded with no filters');
}
contentScripts.clear();
smalluban marked this conversation as resolved.
Show resolved Hide resolved
}

let updating = false;
Expand Down Expand Up @@ -167,7 +168,29 @@ 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 {
set(key, value) {
map.set(key, value);
},
has(key) {
return map.has(key);
},
delete(key) {
const contentScript = map.get(key);
smalluban marked this conversation as resolved.
Show resolved Hide resolved
contentScript.unregister();
map.delete(key);
chrmod marked this conversation as resolved.
Show resolved Hide resolved
},
clear() {
for (const key of map.keys()) {
this.delete(key);
}
},
};
})();

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,25 +219,52 @@ async function injectScriptlets(scripts, tabId, frameId) {
script.remove();
}

chrome.scripting.executeScript(
{
injectImmediately: true,
world:
chrome.scripting.ExecutionWorld?.MAIN ??
(__PLATFORM__ === 'firefox' ? undefined : 'MAIN'),
target: {
tabId,
frameIds: [frameId],
},
func: scriptletInjector,
args: [encodeURIComponent(scriptlets)],
},
() => {
if (chrome.runtime.lastError) {
console.warn(chrome.runtime.lastError);
if (__PLATFORM__ === 'firefox') {
if (scripts.length === 0) {
contentScripts.delete(hostname);
chrmod marked this conversation as resolved.
Show resolved Hide resolved
} else if (!contentScripts.has(hostname)) {
try {
const contentScript = await browser.contentScripts.register({
js: [
{
code: `(${scriptletInjector.toString()})("${encodeURIComponent(scriptlets)}")`,
},
],
allFrames: true,
matches: [`https://*.${hostname}/*`, `http://*.${hostname}/*`],
matchAboutBlank: true,
matchOriginAsFallback: true,
runAt: 'document_start',
});
contentScripts.set(hostname, contentScript);
} catch (e) {
console.warn(e);
contentScripts.delete(hostname);
}
},
);
}
} else {
if (scripts.length === 0) return;

chrome.scripting.executeScript(
{
injectImmediately: true,
world:
chrome.scripting.ExecutionWorld?.MAIN ??
(__PLATFORM__ === 'firefox' ? undefined : 'MAIN'),
target: {
tabId,
frameIds: [frameId],
},
func: scriptletInjector,
args: [encodeURIComponent(scriptlets)],
},
() => {
if (chrome.runtime.lastError) {
console.warn(chrome.runtime.lastError);
}
},
);
}
}

function injectStyles(styles, tabId, frameId) {
Expand Down Expand Up @@ -258,6 +308,7 @@ async function injectCosmetics(details, config) {

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

{
const cosmetics = engine.getCosmeticsFilters({
Expand All @@ -279,8 +330,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 +420,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