mirror of
https://github.com/Dasemu/X-GeoBlock.git
synced 2026-11-26 15:26:09 +00:00
fix: resolve account country from rendered about page
This commit is contained in:
1 parent
3811ae9cfc
commit
d6c31bdf95
5 files changed
+102
-17
No files matched your search
@@ -5,7 +5,7 @@ X GeoBlock is a Manifest V3 browser extension for Chromium and Firefox. While yo
|
||||
## Features
|
||||
|
||||
- Processes posts already on the page and posts loaded by infinite scrolling.
|
||||
- Performs authenticated About-page requests in the extension service worker.
|
||||
- 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.
|
||||
- Caches account results locally without expiration until you clear the cache.
|
||||
- Coalesces duplicate lookups and spaces network requests to reduce load on X.
|
||||
- Skips followed accounts.
|
||||
@@ -53,6 +53,7 @@ The location picker contains the ISO 3166-1 countries, plus Kosovo, using Englis
|
||||
|
||||
- `storage`: saves settings and the local user cache.
|
||||
- `offscreen`: parses returned HTML without opening visible tabs.
|
||||
- `tabs`: opens and closes inactive About tabs when X requires client-side rendering.
|
||||
- `https://x.com/*`: reads About pages and runs the feed filter on X.
|
||||
|
||||
## License
|
||||
|
||||
+72
-13
@@ -4,6 +4,7 @@ const extensionApi = globalThis.browser || chrome;
|
||||
|
||||
const CACHE_KEY = "userCache";
|
||||
const activeRequests = new Map();
|
||||
const pendingTabLookups = new Map();
|
||||
let queueTail = Promise.resolve();
|
||||
let lastRequestAt = 0;
|
||||
|
||||
@@ -12,7 +13,7 @@ extensionApi.runtime.onInstalled.addListener(async () => {
|
||||
await extensionApi.storage.sync.set(current);
|
||||
});
|
||||
|
||||
extensionApi.runtime.onMessage.addListener((message, _sender, sendResponse) => {
|
||||
extensionApi.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||||
if (message?.type === "lookup-user") {
|
||||
lookupUser(message.username).then(sendResponse).catch((error) => {
|
||||
sendResponse({ ok: false, error: error.message });
|
||||
@@ -23,9 +24,22 @@ 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);
|
||||
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);
|
||||
}
|
||||
@@ -45,14 +59,20 @@ async function lookupUserInternal(username, key) {
|
||||
const stored = await extensionApi.storage.local.get(CACHE_KEY);
|
||||
const cache = stored[CACHE_KEY] || {};
|
||||
const cached = cache[key];
|
||||
if (cached) {
|
||||
if (cached && (cached.country || cached.following === true)) {
|
||||
return decision(cached, settings, true);
|
||||
}
|
||||
|
||||
const result = await enqueue(() => fetchAbout(username));
|
||||
cache[key] = { ...result, checkedAt: Date.now() };
|
||||
await extensionApi.storage.local.set({ [CACHE_KEY]: cache });
|
||||
return decision(cache[key], settings, false);
|
||||
const record = { ...result, checkedAt: Date.now() };
|
||||
if (record.country || record.following === true) {
|
||||
cache[key] = record;
|
||||
await extensionApi.storage.local.set({ [CACHE_KEY]: cache });
|
||||
} else if (cached) {
|
||||
delete cache[key];
|
||||
await extensionApi.storage.local.set({ [CACHE_KEY]: cache });
|
||||
}
|
||||
return decision(record, settings, false);
|
||||
}
|
||||
|
||||
function decision(record, settings, cached) {
|
||||
@@ -77,14 +97,23 @@ function enqueue(task) {
|
||||
}
|
||||
|
||||
async function fetchAbout(username) {
|
||||
const response = await fetch(`https://x.com/${encodeURIComponent(username)}/about`, {
|
||||
credentials: "include",
|
||||
headers: { "Accept-Language": "en-US,en;q=0.9" },
|
||||
redirect: "follow"
|
||||
});
|
||||
if (!response.ok) throw new Error(`X returned HTTP ${response.status}`);
|
||||
const html = await response.text();
|
||||
if (/\/i\/flow\/login/i.test(response.url)) throw new Error("X authentication is required");
|
||||
try {
|
||||
const response = await fetch(`https://x.com/${encodeURIComponent(username)}/about`, {
|
||||
credentials: "include",
|
||||
headers: { "Accept-Language": "en-US,en;q=0.9" },
|
||||
redirect: "follow"
|
||||
});
|
||||
if (response.ok && !/\/i\/flow\/login/i.test(response.url)) {
|
||||
const parsed = await parseFetchedHtml(await response.text(), username);
|
||||
if (parsed?.country) return parsed;
|
||||
}
|
||||
} catch (_) {
|
||||
// X frequently serves an incomplete SPA shell to extension fetches.
|
||||
}
|
||||
return lookupViaBackgroundTab(username);
|
||||
}
|
||||
|
||||
async function parseFetchedHtml(html, username) {
|
||||
if (typeof DOMParser !== "undefined" && typeof XGeoParser !== "undefined") {
|
||||
const document = new DOMParser().parseFromString(html, "text/html");
|
||||
return XGeoParser.parseAboutDocument(document, username);
|
||||
@@ -93,6 +122,36 @@ async function fetchAbout(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");
|
||||
|
||||
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`));
|
||||
}, 25000);
|
||||
pendingTabLookups.set(tab.id, { username: username.toLowerCase(), resolve, reject, timer });
|
||||
});
|
||||
}
|
||||
|
||||
function finishTabLookup(tabId, message) {
|
||||
const pending = pendingTabLookups.get(tabId);
|
||||
if (!pending || String(message.username).toLowerCase() !== pending.username) return;
|
||||
clearTimeout(pending.timer);
|
||||
pendingTabLookups.delete(tabId);
|
||||
pending.resolve({
|
||||
country: message.country || null,
|
||||
following: message.following === true,
|
||||
profileLocation: message.profileLocation || null
|
||||
});
|
||||
extensionApi.tabs.remove(tabId).catch(() => {});
|
||||
}
|
||||
|
||||
async function ensureOffscreenDocument() {
|
||||
const url = extensionApi.runtime.getURL("offscreen/offscreen.html");
|
||||
const clients = await self.clients.matchAll();
|
||||
|
||||
+23
@@ -9,6 +9,11 @@ let scanQueued = false;
|
||||
initialize();
|
||||
|
||||
async function initialize() {
|
||||
const aboutMatch = location.pathname.match(/^\/([A-Za-z0-9_]{1,15})\/about\/?$/);
|
||||
if (aboutMatch) {
|
||||
reportRenderedAboutPage(aboutMatch[1]);
|
||||
return;
|
||||
}
|
||||
settings = await extensionApi.storage.sync.get({ enabled: true, showPlaceholder: false });
|
||||
scan(document);
|
||||
new MutationObserver((mutations) => {
|
||||
@@ -16,6 +21,24 @@ async function initialize() {
|
||||
}).observe(document.documentElement, { childList: true, subtree: true });
|
||||
}
|
||||
|
||||
function reportRenderedAboutPage(username) {
|
||||
const startedAt = Date.now();
|
||||
const inspect = () => {
|
||||
const result = XGeoParser.parseAboutDocument(document, username);
|
||||
if (result.country) {
|
||||
extensionApi.runtime.sendMessage({ type: "about-page-result", username, ...result }).catch(() => {});
|
||||
return true;
|
||||
}
|
||||
return Date.now() - startedAt >= 24000;
|
||||
};
|
||||
if (inspect()) return;
|
||||
const observer = new MutationObserver(() => {
|
||||
if (inspect()) observer.disconnect();
|
||||
});
|
||||
observer.observe(document.documentElement, { childList: true, subtree: true, characterData: true });
|
||||
setTimeout(() => observer.disconnect(), 24500);
|
||||
}
|
||||
|
||||
extensionApi.storage.onChanged.addListener((changes, area) => {
|
||||
if (area !== "sync") return;
|
||||
if (changes.enabled) settings.enabled = changes.enabled.newValue;
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
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.
|
||||
3. On a cache miss, the background process requests `https://x.com/<user>/about` with the browser's existing X session.
|
||||
4. Chromium passes the HTML to an offscreen document; Firefox parses it in its background page. The parser locates the location-pin row for the account country and also inspects embedded user data for the `following` relationship.
|
||||
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.
|
||||
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.
|
||||
|
||||
Failed or ambiguous lookups fail open: the post remains visible. Successful lookups remain cached without expiration. The user can clear the entire cache from the settings page if X changes an account's country or following relationship.
|
||||
Failed or ambiguous lookups fail open: the post remains visible. Empty results are never cached. Successful lookups remain cached without expiration. The user can clear the entire cache from the settings page if X changes an account's country or following relationship.
|
||||
|
||||
## Browser components
|
||||
|
||||
|
||||
+3
-1
@@ -11,7 +11,8 @@
|
||||
},
|
||||
"permissions": [
|
||||
"storage",
|
||||
"offscreen"
|
||||
"offscreen",
|
||||
"tabs"
|
||||
],
|
||||
"host_permissions": [
|
||||
"https://x.com/*"
|
||||
@@ -25,6 +26,7 @@
|
||||
"https://x.com/*"
|
||||
],
|
||||
"js": [
|
||||
"lib/parser.js",
|
||||
"content.js"
|
||||
],
|
||||
"css": [
|
||||
|
||||
Reference in new issue
Block a user