Skip to content
Merged
Show file tree
Hide file tree
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
733 changes: 733 additions & 0 deletions extensions/chrome-extension-fb-why/content.js

Large diffs are not rendered by default.

261 changes: 261 additions & 0 deletions extensions/chrome-extension-fb-why/inject.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
/**
* MAIN world: capture WAIST GraphQL; expose last captures for UI flow.
*/
(function () {
const SOURCE = "fb-why-top10";

/** @type {string|null} */
let pendingKey = null;
/** @type {Map<string, object>} */
const whys = new Map();
/** @type {object[]} */
let recent = [];

const origFetch = window.fetch.bind(window);

function emit(type, payload) {
window.postMessage({ source: SOURCE, type, ...payload }, "*");
}

function isGraphqlUrl(url) {
return /\/api\/graphql\/?/i.test(String(url || ""));
}

function walk(obj, fn) {
if (obj == null || typeof obj !== "object") return;
fn(obj);
if (Array.isArray(obj)) {
obj.forEach((v) => walk(v, fn));
return;
}
for (const v of Object.values(obj)) walk(v, fn);
}

function isWaistResponse(data) {
const s = JSON.stringify(data);
return (
s.includes("waist_") ||
s.includes("ifr_waist_explanation") ||
s.includes("WAISTUI") ||
s.includes("waist_explanations") ||
// Organic "why you see this post" payloads (no waist_ prefix)
s.includes("feed_unit_explanation") ||
s.includes("WhyAmISeeingThis") ||
s.includes("why_am_i_seeing") ||
s.includes("RankingExplanation") ||
s.includes("ranking_explanation")
);
}

function pushText(out, v) {
if (v == null) return;
const s = typeof v === "string" ? v.trim() : "";
if (s.length > 8 && s.length < 600 && !out.targeting.includes(s)) {
out.targeting.push(s);
}
}

function extractWhy(data) {
const out = {
kind: "post",
generic: null,
personalized: null,
advertiser: null,
targeting: [],
at: Date.now(),
};

walk(data, (node) => {
if (!node || typeof node !== "object") return;
if (node.ifr_waist_explanation_data) {
out.generic =
node.ifr_waist_explanation_data.generic_explanation || null;
out.personalized =
node.ifr_waist_explanation_data.personalized_explanation || null;
}
if (node.waist_advertiser_info?.name) {
out.kind = "ad";
out.advertiser = node.waist_advertiser_info.name;
}
if (Array.isArray(node.waist_targeting_data)) {
out.kind = "ad";
for (const t of node.waist_targeting_data) {
if (t.waist_ui_type === "AGE_GENDER") {
out.targeting.push(`age ${t.age_min ?? "?"}-${t.age_max ?? "?"}`);
} else if (t.waist_ui_type === "LOCATION" && t.location_name) {
out.targeting.push(`location ${t.location_name}`);
} else if (t.waist_ui_type) {
out.targeting.push(String(t.waist_ui_type));
}
}
}
if (Array.isArray(node.waist_explanations_data)) {
for (const e of node.waist_explanations_data) {
const t = e.title || e.description || e.text || e.headline;
if (t) out.targeting.push(String(t));
}
}
// Organic ranking / follow explanations
if (Array.isArray(node.explanations)) {
for (const e of node.explanations) {
if (typeof e === "string") pushText(out, e);
else if (e && typeof e === "object") {
pushText(out, e.title || e.text || e.description || e.subtitle);
pushText(out, e.body);
}
}
}
if (node.explanation_title || node.explanation_body) {
pushText(out, node.explanation_title);
pushText(out, node.explanation_body);
}
if (node.__typename && /Explanation|Waist|WhyAmISeeing/i.test(node.__typename)) {
pushText(out, node.title || node.text || node.description || node.name);
pushText(out, node.subtitle || node.body);
}
});

if (!out.generic && out.targeting.length) {
out.generic = out.targeting.join(" · ");
}
if (out.advertiser) out.kind = "ad";
else if (
out.targeting.some((x) =>
/age |location |AGE_GENDER|LOCATION|advertiser|sponsored/i.test(x),
)
) {
out.kind = "ad";
}
return out;
}

function parseJsonResponse(text) {
try {
return JSON.parse(text);
} catch {
try {
const lines = text
.split("\n")
.filter(Boolean)
.map((l) => JSON.parse(l));
return lines.length === 1 ? lines[0] : { batch: lines };
} catch {
return null;
}
}
}

function storeWhy(why) {
const key = pendingKey || `waist-${Date.now()}`;
const payload = {
...why,
storyKey: key,
at: Date.now(),
source: why.source || "graphql",
};
// Skip empty extracts
if (
!payload.generic &&
!payload.personalized &&
!payload.advertiser &&
!(payload.targeting && payload.targeting.length)
) {
return;
}
whys.set(key, payload);
recent.push(payload);
if (recent.length > 20) recent.shift();
window.__fbWhyLast = payload;
emit("why", { key, why: payload });
emit("state", { whys: Object.fromEntries(whys), recent: recent.slice(-5) });
console.info(
"[fb-why] captured",
key,
why.kind,
why.advertiser || why.generic?.slice?.(0, 60),
);
}

function handleResponseText(text) {
const data = parseJsonResponse(text);
if (!data) return;
// batch of JSON objects
if (data.batch && Array.isArray(data.batch)) {
for (const part of data.batch) {
if (isWaistResponse(part)) storeWhy(extractWhy(part));
}
return;
}
if (!isWaistResponse(data)) return;
storeWhy(extractWhy(data));
}

window.fetch = async function (...args) {
const input = args[0];
const url =
typeof input === "string"
? input
: input instanceof Request
? input.url
: String(input?.url ?? "");
const res = await origFetch(...args);
if (isGraphqlUrl(url)) {
try {
const clone = res.clone();
void clone.text().then(handleResponseText);
} catch {
/* ignore */
}
}
return res;
};

const OrigXHR = window.XMLHttpRequest;
function PatchedXHR() {
const xhr = new OrigXHR();
let url = "";
const open = xhr.open;
xhr.open = function (method, u, ...rest) {
url = String(u || "");
return open.call(xhr, method, u, ...rest);
};
xhr.addEventListener("load", function () {
if (!isGraphqlUrl(url)) return;
try {
handleResponseText(xhr.responseText);
} catch {
/* ignore */
}
});
return xhr;
}
PatchedXHR.prototype = OrigXHR.prototype;
window.XMLHttpRequest = PatchedXHR;

window.addEventListener("message", (event) => {
if (event.source !== window) return;
const data = event.data;
if (!data || data.source !== SOURCE) return;
if (data.type === "set-pending") {
pendingKey = data.key || null;
window.__fbWhyPending = pendingKey;
}
if (data.type === "ping") {
emit("state", {
whys: Object.fromEntries(whys),
recent: recent.slice(-5),
});
}
if (data.type === "claim-recent") {
const since = data.since || 0;
const hit = [...recent].reverse().find((w) => (w.at || 0) > since);
if (hit) {
const key = data.key || hit.storyKey;
whys.set(key, { ...hit, storyKey: key });
emit("why", { key, why: whys.get(key) });
}
}
});

console.info("[fb-why] inject ready (capture + recent buffer)");
})();
36 changes: 36 additions & 0 deletions extensions/chrome-extension-fb-why/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"manifest_version": 3,
"name": "FB Why Top 10",
"version": "0.3.0",
"description": "Fetch Why for 5 Facebook feed posts (GraphQL + DOM), scrolling as needed.",
"host_permissions": [
"https://www.facebook.com/*",
"https://web.facebook.com/*",
"https://facebook.com/*",
"https://m.facebook.com/*"
],
"content_scripts": [
{
"matches": [
"https://www.facebook.com/*",
"https://web.facebook.com/*",
"https://facebook.com/*",
"https://m.facebook.com/*"
],
"js": ["content.js"],
"css": ["styles.css"],
"run_at": "document_start"
},
{
"matches": [
"https://www.facebook.com/*",
"https://web.facebook.com/*",
"https://facebook.com/*",
"https://m.facebook.com/*"
],
"js": ["inject.js"],
"run_at": "document_start",
"world": "MAIN"
}
]
}
82 changes: 82 additions & 0 deletions extensions/chrome-extension-fb-why/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
.fb-why-panel {
position: fixed;
top: 72px;
right: 16px;
z-index: 2147483646;
width: 320px;
max-height: calc(100vh - 96px);
overflow: auto;
padding: 12px;
border-radius: 12px;
background: rgba(15, 20, 25, 0.95);
color: #e7e9ea;
border: 1px solid rgba(255, 255, 255, 0.14);
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.45);
font: 12px/1.4 system-ui, -apple-system, sans-serif;
}

.fb-why-fetch {
appearance: none;
border: 0;
border-radius: 8px;
width: 100%;
padding: 8px 12px;
background: #1d9bf0;
color: #fff;
font: inherit;
font-weight: 700;
cursor: pointer;
}

.fb-why-fetch:disabled {
opacity: 0.55;
cursor: wait;
}

.fb-why-status {
margin: 8px 0 0;
color: #1d9bf0;
font-weight: 600;
min-height: 1.2em;
}

.fb-why-list {
margin: 10px 0 0;
padding-left: 18px;
}

.fb-why-list li {
margin-bottom: 10px;
}

.fb-why-empty {
list-style: none;
margin-left: -18px;
color: #8b98a5;
font-size: 11px;
}

.fb-why-item-head {
display: flex;
gap: 6px;
align-items: baseline;
margin-bottom: 4px;
}

.fb-why-item-head .tag {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
color: #8b98a5;
}

.fb-why-text {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
background: rgba(255, 255, 255, 0.04);
border-radius: 8px;
padding: 6px 8px;
font: 11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace;
color: #d7dbe0;
}
Loading
Loading