fix: render account data in isolated background frame

This commit is contained in:
Darío Sevilla committed 2026-10-15 07:46:54 +00:00
1 parent d6c31bdf95
commit 7e88fee0c2
7 files changed
+107 -37

No files matched your search

+2 -2
View File
@@ -5,7 +5,7 @@ X GeoBlock is a Manifest V3 browser extension for Chromium and Firefox. While yo
## Features ## Features
- Processes posts already on the page and posts loaded by infinite scrolling. - Processes posts already on the page and posts loaded by infinite scrolling.
- Performs authenticated About-page requests in the background. If X returns only its empty application shell, the extension briefly uses an inactive tab so X can render the account data, then closes it automatically. - Performs authenticated About-page requests in the background. If X returns only its empty application shell, an isolated invisible extension frame renders the account data without opening tabs or windows.
- Caches account results locally without expiration until you clear the cache. - Caches account results locally without expiration until you clear the cache.
- Coalesces duplicate lookups and spaces network requests to reduce load on X. - Coalesces duplicate lookups and spaces network requests to reduce load on X.
- Skips followed accounts. - Skips followed accounts.
@@ -53,7 +53,7 @@ The location picker contains the ISO 3166-1 countries, plus Kosovo, using Englis
- `storage`: saves settings and the local user cache. - `storage`: saves settings and the local user cache.
- `offscreen`: parses returned HTML without opening visible tabs. - `offscreen`: parses returned HTML without opening visible tabs.
- `tabs`: opens and closes inactive About tabs when X requires client-side rendering. - `declarativeNetRequestWithHostAccess`: permits only `x.com` subframes to render inside the isolated background document after X returns an empty application shell.
- `https://x.com/*`: reads About pages and runs the feed filter on X. - `https://x.com/*`: reads About pages and runs the feed filter on X.
## License ## License
+76 -30
View File
@@ -3,14 +3,16 @@ if (typeof XGeoConfig === "undefined") importScripts("lib/config.js");
const extensionApi = globalThis.browser || chrome; const extensionApi = globalThis.browser || chrome;
const CACHE_KEY = "userCache"; const CACHE_KEY = "userCache";
const FRAME_RULE_ID = 1;
const activeRequests = new Map(); const activeRequests = new Map();
const pendingTabLookups = new Map(); const pendingFrameLookups = new Map();
let queueTail = Promise.resolve(); let queueTail = Promise.resolve();
let lastRequestAt = 0; let lastRequestAt = 0;
extensionApi.runtime.onInstalled.addListener(async () => { extensionApi.runtime.onInstalled.addListener(async () => {
const current = await extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS); const current = await extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS);
await extensionApi.storage.sync.set(current); await extensionApi.storage.sync.set(current);
await ensureFrameRule();
}); });
extensionApi.runtime.onMessage.addListener((message, sender, sendResponse) => { extensionApi.runtime.onMessage.addListener((message, sender, sendResponse) => {
@@ -24,22 +26,14 @@ extensionApi.runtime.onMessage.addListener((message, sender, sendResponse) => {
extensionApi.storage.local.remove(CACHE_KEY).then(() => sendResponse({ ok: true })); extensionApi.storage.local.remove(CACHE_KEY).then(() => sendResponse({ ok: true }));
return true; return true;
} }
if (message?.type === "about-page-result" && Number.isInteger(sender?.tab?.id)) { if (message?.type === "about-page-result") {
finishTabLookup(sender.tab.id, message); finishFrameLookup(message);
sendResponse({ ok: true }); sendResponse({ ok: true });
return false; return false;
} }
return false; return false;
}); });
extensionApi.tabs.onRemoved.addListener((tabId) => {
const pending = pendingTabLookups.get(tabId);
if (!pending) return;
clearTimeout(pending.timer);
pendingTabLookups.delete(tabId);
pending.reject(new Error("The background About tab closed before X loaded the account data"));
});
function validUsername(username) { function validUsername(username) {
return typeof username === "string" && /^[A-Za-z0-9_]{1,15}$/.test(username); return typeof username === "string" && /^[A-Za-z0-9_]{1,15}$/.test(username);
} }
@@ -110,7 +104,7 @@ async function fetchAbout(username) {
} catch (_) { } catch (_) {
// X frequently serves an incomplete SPA shell to extension fetches. // X frequently serves an incomplete SPA shell to extension fetches.
} }
return lookupViaBackgroundTab(username); return lookupViaBackgroundFrame(username);
} }
async function parseFetchedHtml(html, username) { async function parseFetchedHtml(html, username) {
@@ -122,34 +116,86 @@ async function parseFetchedHtml(html, username) {
return extensionApi.runtime.sendMessage({ type: "parse-about-html", html, username }); return extensionApi.runtime.sendMessage({ type: "parse-about-html", html, username });
} }
async function lookupViaBackgroundTab(username) { async function lookupViaBackgroundFrame(username) {
const tab = await extensionApi.tabs.create({ const key = username.toLowerCase();
url: `https://x.com/${encodeURIComponent(username)}/about`,
active: false
});
if (!Number.isInteger(tab.id)) throw new Error("The browser did not create the background About tab");
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const timer = setTimeout(() => { const timer = setTimeout(() => {
pendingTabLookups.delete(tab.id); pendingFrameLookups.delete(key);
extensionApi.tabs.remove(tab.id).catch(() => {}); removeBackgroundFrame(key);
reject(new Error(`Timed out while loading @${username}'s About page`)); reject(new Error(`Timed out while rendering @${username}'s About page in the background`));
}, 25000); }, 25000);
pendingTabLookups.set(tab.id, { username: username.toLowerCase(), resolve, reject, timer }); pendingFrameLookups.set(key, { resolve, reject, timer });
createBackgroundFrame(username).catch((error) => {
clearTimeout(timer);
pendingFrameLookups.delete(key);
reject(error);
});
}); });
} }
function finishTabLookup(tabId, message) { function finishFrameLookup(message) {
const pending = pendingTabLookups.get(tabId); const key = String(message.username).toLowerCase();
if (!pending || String(message.username).toLowerCase() !== pending.username) return; const pending = pendingFrameLookups.get(key);
if (!pending) return;
clearTimeout(pending.timer); clearTimeout(pending.timer);
pendingTabLookups.delete(tabId); pendingFrameLookups.delete(key);
pending.resolve({ pending.resolve({
country: message.country || null, country: message.country || null,
following: message.following === true, following: message.following === true,
profileLocation: message.profileLocation || null profileLocation: message.profileLocation || null
}); });
extensionApi.tabs.remove(tabId).catch(() => {}); removeBackgroundFrame(key);
}
async function createBackgroundFrame(username) {
await ensureFrameRule();
if (typeof document !== "undefined") {
const frame = document.createElement("iframe");
frame.dataset.xGeoBlockUser = username.toLowerCase();
frame.hidden = true;
frame.src = `https://x.com/${encodeURIComponent(username)}/about`;
document.body.append(frame);
return;
}
await ensureOffscreenDocument();
await extensionApi.runtime.sendMessage({ type: "create-about-frame", username });
}
let frameRulePromise;
function ensureFrameRule() {
if (!frameRulePromise) {
frameRulePromise = extensionApi.declarativeNetRequest.updateSessionRules({
removeRuleIds: [FRAME_RULE_ID],
addRules: [{
id: FRAME_RULE_ID,
priority: 1,
action: {
type: "modifyHeaders",
responseHeaders: [
{ header: "x-frame-options", operation: "remove" },
{ header: "content-security-policy", operation: "remove" }
]
},
condition: {
urlFilter: "||x.com/",
resourceTypes: ["sub_frame"],
tabIds: [-1]
}
}]
}).catch((error) => {
frameRulePromise = null;
throw error;
});
}
return frameRulePromise;
}
function removeBackgroundFrame(username) {
if (typeof document !== "undefined") {
document.querySelector(`iframe[data-x-geo-block-user="${CSS.escape(username)}"]`)?.remove();
return;
}
extensionApi.runtime.sendMessage({ type: "remove-about-frame", username }).catch(() => {});
} }
async function ensureOffscreenDocument() { async function ensureOffscreenDocument() {
@@ -158,7 +204,7 @@ async function ensureOffscreenDocument() {
if (clients.some((client) => client.url === url)) return; if (clients.some((client) => client.url === url)) return;
await extensionApi.offscreen.createDocument({ await extensionApi.offscreen.createDocument({
url: "offscreen/offscreen.html", url: "offscreen/offscreen.html",
reasons: ["DOM_PARSER"], reasons: ["DOM_PARSER", "IFRAME_SCRIPTING"],
justification: "Parse the account About page without opening a visible tab." justification: "Parse and render account About pages entirely in the extension background."
}); });
} }
+1
View File
@@ -14,6 +14,7 @@ async function initialize() {
reportRenderedAboutPage(aboutMatch[1]); reportRenderedAboutPage(aboutMatch[1]);
return; return;
} }
if (window.top !== window) return;
settings = await extensionApi.storage.sync.get({ enabled: true, showPlaceholder: false }); settings = await extensionApi.storage.sync.get({ enabled: true, showPlaceholder: false });
scan(document); scan(document);
new MutationObserver((mutations) => { new MutationObserver((mutations) => {
+1 -1
View File
@@ -5,7 +5,7 @@
1. The content script observes X's timeline and extracts an author from each canonical `/user/status/id` link. 1. The content script observes X's timeline and extracts an author from each canonical `/user/status/id` link.
2. The service worker checks the local cache and coalesces concurrent lookups for the same username. 2. The service worker checks the local cache and coalesces concurrent lookups for the same username.
3. On a cache miss, the background process requests `https://x.com/<user>/about` with the browser's existing X session. 3. On a cache miss, the background process requests `https://x.com/<user>/about` with the browser's existing X session.
4. Chromium passes fetched HTML to an offscreen document; Firefox can parse it in its background page. When X returns only its SPA shell, the extension opens the same URL in an inactive tab, waits for X to render the location row, reports the result, and closes the tab. 4. Chromium passes fetched HTML to an offscreen document; Firefox can parse it in its background page. When X returns only its SPA shell, an invisible frame inside the isolated background document renders the same URL, reports the location row, and is immediately destroyed. This does not create a browser tab or window.
5. The worker caches the result and compares the country with the configured blacklist. 5. The worker caches the result and compares the country with the configured blacklist.
6. The content script hides the post only when the country matches and the account is not followed. 6. The content script hides the post only when the country matches and the account is not followed.
+3 -2
View File
@@ -12,7 +12,7 @@
"permissions": [ "permissions": [
"storage", "storage",
"offscreen", "offscreen",
"tabs" "declarativeNetRequestWithHostAccess"
], ],
"host_permissions": [ "host_permissions": [
"https://x.com/*" "https://x.com/*"
@@ -32,7 +32,8 @@
"css": [ "css": [
"content.css" "content.css"
], ],
"run_at": "document_idle" "run_at": "document_idle",
"all_frames": true
} }
], ],
"options_page": "options/options.html", "options_page": "options/options.html",
+1 -1
View File
@@ -1,3 +1,3 @@
<!doctype html> <!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>X GeoBlock parser</title></head> <html lang="en"><head><meta charset="utf-8"><title>X GeoBlock parser</title></head>
<body><script src="../lib/parser.js"></script><script src="offscreen.js"></script></body></html> <body><div id="frames"></div><script src="../lib/parser.js"></script><script src="offscreen.js"></script></body></html>
+23 -1
View File
@@ -3,7 +3,7 @@
const extensionApi = globalThis.browser || chrome; const extensionApi = globalThis.browser || chrome;
extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => { extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type !== "parse-about-html") return false; if (message?.type === "parse-about-html") {
try { try {
const document = new DOMParser().parseFromString(message.html, "text/html"); const document = new DOMParser().parseFromString(message.html, "text/html");
sendResponse(XGeoParser.parseAboutDocument(document, message.username)); sendResponse(XGeoParser.parseAboutDocument(document, message.username));
@@ -11,4 +11,26 @@ extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
sendResponse({ country: null, following: null, error: error.message }); sendResponse({ country: null, following: null, error: error.message });
} }
return false; return false;
}
if (message?.type === "create-about-frame") {
removeFrame(message.username);
const frame = document.createElement("iframe");
frame.dataset.xGeoBlockUser = message.username.toLowerCase();
frame.hidden = true;
frame.src = `https://x.com/${encodeURIComponent(message.username)}/about`;
document.querySelector("#frames").append(frame);
sendResponse({ ok: true });
return false;
}
if (message?.type === "remove-about-frame") {
removeFrame(message.username);
sendResponse({ ok: true });
return false;
}
return false;
}); });
function removeFrame(username) {
const key = String(username).toLowerCase();
document.querySelector(`iframe[data-x-geo-block-user="${CSS.escape(key)}"]`)?.remove();
}