-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
514 lines (430 loc) · 15.6 KB
/
content.js
File metadata and controls
514 lines (430 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// PostPolice Content Script
// Extracts verifiable content from any webpage using local AI
// Logs summary to console
(function () {
"use strict";
// ============================================
// CONFIGURATION
// ============================================
// Selectors for content elements to extract text from
const CONTENT_SELECTORS = [
"p",
"span",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"li",
"td",
"th",
"blockquote",
"article",
"section",
'[data-testid="tweetText"]', // Twitter/X specific
];
// Selectors for elements to ignore
const IGNORE_SELECTORS = [
"script",
"style",
"noscript",
"nav",
"header",
"footer",
"aside",
"iframe",
"svg",
"canvas",
"video",
"audio",
".nav",
".navbar",
".header",
".footer",
".sidebar",
".menu",
".ad",
".advertisement",
'[role="navigation"]',
'[role="banner"]',
'[role="contentinfo"]',
];
// Minimum text length to consider for analysis
const MIN_TEXT_LENGTH = 20;
// Debounce delay for MutationObserver (ms)
const DEBOUNCE_DELAY = 2000;
// ============================================
// STATE
// ============================================
let aiAvailable = false;
const processedNodes = new WeakSet();
let debounceTimer = null;
let isProcessing = false;
// Store summaries for verification
const summaries = [];
// Store verification results (contains claims and their source links)
const verificationResults = [];
// Store all links organized by claim
const claimLinks = [];
// Expose globally for external access
window.postPoliceSummaries = summaries;
window.postPoliceVerifications = verificationResults;
window.postPoliceLinks = claimLinks;
// ============================================
// VERIFICATION SEARCH
// ============================================
/**
* Searches for verification sources for a claim.
* @param {string} claim - The claim to search for
* @returns {Promise<{claim: string, sources: Array}>}
*/
async function searchForClaim(claim) {
try {
const response = await chrome.runtime.sendMessage({
type: "SEARCH_CLAIM",
claim: claim,
});
return response;
} catch (error) {
console.log("PostPolice: Search failed:", error.message);
return { claim, sources: [] };
}
}
/**
* Fact-checks a claim using scraped links: fetches HTML from links and gets Gemini verdict.
* @param {string} statement - The claim to verify
* @param {string[]} links - URLs (e.g. from DuckDuckGo results)
* @returns {Promise<{verdict: string, reasoning: string, raw: string, htmlSize: number}>}
*/
async function verifyClaimWithLinks(statement, links) {
try {
const response = await chrome.runtime.sendMessage({
type: "VERIFY_FACT",
statement: statement,
links: links,
});
return response || { verdict: "UNCERTAIN", reasoning: "No response", raw: "", htmlSize: 0 };
} catch (error) {
console.log("PostPolice: Fact check failed:", error.message);
return { verdict: "UNCERTAIN", reasoning: error.message, raw: "", htmlSize: 0 };
}
}
/**
* Searches for verification sources for all stored summaries.
* Call this from console: window.postPoliceVerify()
*/
async function verifyAllSummaries() {
console.log("PostPolice: Starting verification for", summaries.length, "summaries...");
for (let i = 0; i < summaries.length; i++) {
const summary = summaries[i];
console.log(`\nPostPolice: Searching for summary ${i + 1}/${summaries.length}...`);
console.log("Summary:", summary.summary.substring(0, 100) + "...");
const result = await searchForClaim(summary.summary);
verificationResults.push({
summaryIndex: i,
summary: summary.summary,
sources: result.sources,
searchedAt: result.searchedAt,
});
if (result.sources.length > 0) {
console.log(`Found ${result.sources.length} sources from credible news sites:`);
result.sources.forEach((source, j) => {
console.log(` ${j + 1}. ${source.title}`);
console.log(` URL: ${source.url}`);
console.log(` Snippet: ${source.snippet}`);
});
} else {
console.log("No sources found from whitelisted news sites.");
}
}
console.log("\n=== Verification Complete ===");
console.log("Results stored in window.postPoliceVerifications");
return verificationResults;
}
// Expose verify function globally
window.postPoliceVerify = verifyAllSummaries;
window.postPoliceSearch = searchForClaim;
// ============================================
// UI HIGHLIGHTING
// ============================================
/**
* Highlights a claim on the page based on its verdict.
*/
function highlightClaimOnPage(claim, verdict, reasoning, elements) {
if (verdict === "VERIFIED") return;
const className = verdict === "FALSE" ? "postpolice-false" : "postpolice-uncertain";
const label = verdict === "FALSE" ? "FALSE CLAIM" : "UNCERTAIN";
console.log(`PostPolice: Highlighting ${label}: "${claim.substring(0, 30)}..."`);
elements.forEach(({ element, text }) => {
if (element.dataset.postpoliceHighlighted) return;
const normalizedElementText = text.toLowerCase();
const normalizedClaim = claim.toLowerCase();
const claimWords = normalizedClaim.split(/\s+/).filter(w => w.length > 3);
const matchCount = claimWords.filter(w => normalizedElementText.includes(w)).length;
const matchRatio = matchCount / claimWords.length;
if (matchRatio > 0.4 || normalizedElementText.includes(normalizedClaim) || normalizedClaim.includes(normalizedElementText)) {
element.classList.add(className);
element.title = `${label}: ${reasoning}`;
element.dataset.postpoliceHighlighted = "true";
if (verdict === "FALSE" && !element.querySelector('.postpolice-badge')) {
const badge = document.createElement('span');
badge.className = 'postpolice-badge';
badge.textContent = ' 🚩 FALSE';
badge.style.fontSize = '0.7em';
badge.style.fontWeight = 'bold';
badge.style.color = '#ef4444';
badge.style.marginLeft = '5px';
element.appendChild(badge);
}
}
});
}
// ============================================
// TEXT EXTRACTION
// ============================================
function shouldIgnoreElement(element) {
if (!element || !element.tagName) return true;
for (const selector of IGNORE_SELECTORS) {
try {
if (element.matches(selector)) return true;
if (element.closest(selector)) return true;
} catch (e) { }
}
const style = window.getComputedStyle(element);
if (style.display === "none" || style.visibility === "hidden") {
return true;
}
return false;
}
function getDirectTextContent(element) {
let text = "";
for (const node of element.childNodes) {
if (node.nodeType === Node.TEXT_NODE) {
text += node.textContent;
}
}
if (!text.trim()) {
text = element.textContent || "";
}
return text;
}
function extractVisibleText() {
const results = [];
const selector = CONTENT_SELECTORS.join(", ");
const elements = document.querySelectorAll(selector);
elements.forEach((element) => {
if (processedNodes.has(element)) return;
if (shouldIgnoreElement(element)) return;
const text = getDirectTextContent(element).trim();
if (text.length < MIN_TEXT_LENGTH) return;
results.push({ element, text });
});
return results;
}
// ============================================
// LLM INTERACTION
// ============================================
async function checkAI() {
try {
const response = await chrome.runtime.sendMessage({ type: "CHECK_AI" });
aiAvailable = response?.available || false;
console.log("PostPolice: AI available:", aiAvailable);
} catch (error) {
console.log("PostPolice: Could not check AI status:", error.message);
aiAvailable = false;
}
}
async function extractSummaryWithAI(content) {
if (!aiAvailable || !content) {
return "";
}
try {
console.log(`PostPolice: Analyzing content (${content.length} chars)...`);
const response = await chrome.runtime.sendMessage({
type: "EXTRACT_SUMMARY",
content: content,
});
return response?.summary || "";
} catch (error) {
console.log("PostPolice: Summary extraction failed:", error.message);
return "";
}
}
// ============================================
// MAIN PROCESSING
// ============================================
async function scanPage() {
if (isProcessing || !aiAvailable) return;
isProcessing = true;
// Clear previous results to prevent accumulation across scans (MutationObserver)
summaries.length = 0;
verificationResults.length = 0;
claimLinks.length = 0;
console.log("PostPolice: Scanning page for verifiable content...");
try {
const elements = extractVisibleText();
console.log(`PostPolice: Found ${elements.length} text elements`);
if (elements.length === 0) {
isProcessing = false;
return;
}
// Mark elements as processed
elements.forEach(({ element }) => processedNodes.add(element));
// Combine all text content
const fullContent = elements.map(({ text }) => text).join("\n\n");
console.log(`PostPolice: Combined content: ${fullContent.length} chars`);
// Extract summary using AI
const summary = await extractSummaryWithAI(fullContent);
if (summary) {
// Store summary in array for verification
const summaryObj = {
summary: summary,
timestamp: Date.now(),
url: window.location.href,
};
summaries.push(summaryObj);
console.log("=== PostPolice: Verifiable Content Summary ===");
console.log(summary);
console.log("==============================================");
// Split summary into individual claims (by newlines or bullet points)
// STRICTLY LIMIT TO TOP 5 CLAIMS
const claims = summary
.split(/\n|(?=- )/)
.map(line => line.replace(/^[-•*]\s*/, '').trim())
.filter(line => line.length > 10)
.slice(0, 5);
console.log(`\nPostPolice: Found ${claims.length} individual claims to verify (max 5 enforced)`);
// Search for each claim separately, then fact-check using scraped links
for (let i = 0; i < claims.length; i++) {
const claim = claims[i];
console.log(`\n--- Searching claim ${i + 1}/${claims.length}: "${claim.substring(0, 60)}..." ---`);
const searchResult = await searchForClaim(claim);
// Extract just the URLs from sources
const links = searchResult.sources.map(source => source.url);
// Store claim with its links
const claimLinkObj = {
claim: claim,
links: links,
sources: searchResult.sources,
searchedAt: searchResult.searchedAt,
};
claimLinks.push(claimLinkObj);
const verificationObj = {
summaryIndex: summaries.length - 1,
claim: claim,
sources: searchResult.sources,
searchedAt: searchResult.searchedAt,
};
verificationResults.push(verificationObj);
if (searchResult.sources.length > 0) {
console.log(`Found ${searchResult.sources.length} sources:`);
searchResult.sources.forEach((source, j) => {
console.log(` ${j + 1}. ${source.title}`);
console.log(` URL: ${source.url}`);
});
console.log(`Links array: [${links.join(', ')}]`);
// Fact-check: fetch HTML from links and get Gemini verdict
console.log(`PostPolice: Fact-checking claim against ${links.length} link(s)...`);
const verdictResult = await verifyClaimWithLinks(claim, links);
claimLinkObj.verdict = verdictResult.verdict;
claimLinkObj.reasoning = verdictResult.reasoning;
claimLinkObj.raw = verdictResult.raw;
claimLinkObj.htmlSize = verdictResult.htmlSize;
verificationObj.verdict = verdictResult.verdict;
verificationObj.reasoning = verdictResult.reasoning;
verificationObj.raw = verdictResult.raw;
verificationObj.htmlSize = verdictResult.htmlSize;
console.log(`PostPolice: Verdict for claim: ${verdictResult.verdict}`);
console.log(`PostPolice: Reasoning: ${verdictResult.reasoning || '(none)'}`);
// Highlight the claim on the page
highlightClaimOnPage(claim, verdictResult.verdict, verdictResult.reasoning, elements);
} else {
console.log("No sources found for this claim.");
}
// Small delay between searches to avoid rate limiting
if (i < claims.length - 1) {
await new Promise(resolve => setTimeout(resolve, 500));
}
}
console.log("\n=== PostPolice: Verification Complete ===");
console.log("All claim links and verdicts stored in window.postPoliceLinks and window.postPoliceVerifications");
claimLinks.forEach((item, idx) => {
console.log(` Claim ${idx + 1}: ${item.verdict || "—"} | ${(item.claim || "").substring(0, 50)}...`);
});
console.log(claimLinks);
} else {
console.log("PostPolice: No verifiable content found");
}
} catch (error) {
console.log("PostPolice: Error scanning page:", error.message);
}
isProcessing = false;
}
// ============================================
// MUTATION OBSERVER
// ============================================
function debouncedScan() {
if (debounceTimer) {
clearTimeout(debounceTimer);
}
debounceTimer = setTimeout(() => {
scanPage();
debounceTimer = null;
}, DEBOUNCE_DELAY);
}
function setupMutationObserver() {
const observer = new MutationObserver((mutations) => {
let hasNewContent = false;
for (const mutation of mutations) {
if (mutation.addedNodes.length > 0) {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
const element = node;
if (
CONTENT_SELECTORS.some((sel) => {
try {
return element.matches(sel) || element.querySelector(sel);
} catch {
return false;
}
})
) {
hasNewContent = true;
break;
}
}
}
}
if (hasNewContent) break;
}
if (hasNewContent) {
debouncedScan();
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
console.log("PostPolice: MutationObserver active for dynamic content");
return observer;
}
// ============================================
// INITIALIZATION
// ============================================
async function init() {
console.log("PostPolice: Initializing on", window.location.href);
await checkAI();
if (!aiAvailable) {
console.log("PostPolice: AI not available, extension disabled");
return;
}
await scanPage();
setupMutationObserver();
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
})();