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
+112 -42

No files matched your search

+76 -30
View File
@@ -3,14 +3,16 @@ if (typeof XGeoConfig === "undefined") importScripts("lib/config.js");
const extensionApi = globalThis.browser || chrome;
const CACHE_KEY = "userCache";
const FRAME_RULE_ID = 1;
const activeRequests = new Map();
const pendingTabLookups = new Map();
const pendingFrameLookups = new Map();
let queueTail = Promise.resolve();
let lastRequestAt = 0;
extensionApi.runtime.onInstalled.addListener(async () => {
const current = await extensionApi.storage.sync.get(XGeoConfig.DEFAULT_SETTINGS);
await extensionApi.storage.sync.set(current);
await ensureFrameRule();
});
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 }));
return true;
}
if (message?.type === "about-page-result" && Number.isInteger(sender?.tab?.id)) {
finishTabLookup(sender.tab.id, message);
if (message?.type === "about-page-result") {
finishFrameLookup(message);
sendResponse({ ok: true });
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) {
return typeof username === "string" && /^[A-Za-z0-9_]{1,15}$/.test(username);
}
@@ -110,7 +104,7 @@ async function fetchAbout(username) {
} catch (_) {
// X frequently serves an incomplete SPA shell to extension fetches.
}
return lookupViaBackgroundTab(username);
return lookupViaBackgroundFrame(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 });
}
async function lookupViaBackgroundTab(username) {
const tab = await extensionApi.tabs.create({
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");
async function lookupViaBackgroundFrame(username) {
const key = username.toLowerCase();
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingTabLookups.delete(tab.id);
extensionApi.tabs.remove(tab.id).catch(() => {});
reject(new Error(`Timed out while loading @${username}'s About page`));
pendingFrameLookups.delete(key);
removeBackgroundFrame(key);
reject(new Error(`Timed out while rendering @${username}'s About page in the background`));
}, 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) {
const pending = pendingTabLookups.get(tabId);
if (!pending || String(message.username).toLowerCase() !== pending.username) return;
function finishFrameLookup(message) {
const key = String(message.username).toLowerCase();
const pending = pendingFrameLookups.get(key);
if (!pending) return;
clearTimeout(pending.timer);
pendingTabLookups.delete(tabId);
pendingFrameLookups.delete(key);
pending.resolve({
country: message.country || null,
following: message.following === true,
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() {
@@ -158,7 +204,7 @@ async function ensureOffscreenDocument() {
if (clients.some((client) => client.url === url)) return;
await extensionApi.offscreen.createDocument({
url: "offscreen/offscreen.html",
reasons: ["DOM_PARSER"],
justification: "Parse the account About page without opening a visible tab."
reasons: ["DOM_PARSER", "IFRAME_SCRIPTING"],
justification: "Parse and render account About pages entirely in the extension background."
});
}