-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
370 lines (331 loc) · 15 KB
/
content.js
File metadata and controls
370 lines (331 loc) · 15 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
// content.js - Retraction Checker v2.0 (with citation scanning)
(function () {
if (window.__retractionCheckerLoaded) return;
window.__retractionCheckerLoaded = true;
const CACHE_TTL = 86400000; // 24 hours
// ─── DOI Utilities ────────────────────────────────────────────────────
const DOI_PATTERNS = [
/\b(10\.\d{4,9}\/[^\s"'<>]+)/gi,
/doi\.org\/(10\.[^\s"'<>]+)/gi,
/doi:\s*(10\.[^\s"'<>,;]+)/gi,
];
const META_SELECTORS = [
'meta[name="dc.identifier"]',
'meta[name="DC.identifier"]',
'meta[name="citation_doi"]',
'meta[scheme="doi"]',
];
function cleanDOI(doi) {
return (doi || '').replace(/[.,;)\]>'"]+$/, '').toLowerCase().trim();
}
function extractPrimaryDOI() {
for (const selector of META_SELECTORS) {
const el = document.querySelector(selector);
if (el) {
const content = el.getAttribute('content') || el.getAttribute('href') || '';
const match = content.match(/10\.\d{4,9}\/[^\s"'<>]+/);
if (match) return cleanDOI(match[0]);
}
}
const urlMatch = window.location.href.match(/10\.\d{4,9}\/[^\s"'<>?#&]+/);
if (urlMatch) return cleanDOI(urlMatch[0]);
const bodyText = document.body?.innerText?.substring(0, 3000) || '';
for (const pattern of DOI_PATTERNS) {
pattern.lastIndex = 0;
const match = pattern.exec(bodyText);
if (match) return cleanDOI(match[1] || match[0]);
}
return null;
}
// ─── CrossRef API ─────────────────────────────────────────────────────
async function fetchCrossRef(doi) {
const res = await fetch(
`https://api.crossref.org/works/${encodeURIComponent(doi)}`,
{ headers: { 'User-Agent': 'RetractionChecker/2.0 (research-integrity-tool)' } }
);
if (!res.ok) return null;
const data = await res.json();
return data?.message || null;
}
function isRetractedWork(work) {
if (!work) return { retracted: false };
const type = (work.type || '').toLowerCase();
const subtype = (work.subtype || '').toLowerCase();
const title = (work.title?.[0] || '').toLowerCase();
const updates = work.update || work.relation?.['is-retracted-by'];
if (type === 'retraction' || subtype === 'retraction') {
return { retracted: true, reason: 'Retraction notice type detected via CrossRef' };
}
if (updates && updates.length > 0) {
const noticeUrl = updates[0]?.DOI ? `https://doi.org/${updates[0].DOI}` : work.URL;
return { retracted: true, reason: 'Paper has a retraction update record', noticeUrl };
}
if (title.includes('retraction') || title.includes('retracted')) {
return { retracted: true, reason: 'Title indicates retraction' };
}
return { retracted: false };
}
function extractPaperInfo(work) {
if (!work) return null;
return {
title: work.title?.[0] || 'Unknown title',
journal: work['container-title']?.[0] || '',
year: work.issued?.['date-parts']?.[0]?.[0] || '',
authors: (work.author || []).slice(0, 3)
.map(a => `${a.given || ''} ${a.family || ''}`.trim()).join(', '),
};
}
// ─── Retraction Check (single DOI, cached) ────────────────────────────
async function checkRetraction(doi) {
const cacheKey = `rc2_${doi}`;
try {
const cached = await chrome.storage.local.get(cacheKey);
if (cached[cacheKey] && Date.now() - cached[cacheKey].timestamp < CACHE_TTL) {
return cached[cacheKey].result;
}
} catch (_) {}
let result = { retracted: false, doi };
try {
const work = await fetchCrossRef(doi);
if (work) {
const { retracted, reason, noticeUrl } = isRetractedWork(work);
const info = extractPaperInfo(work);
result = {
retracted,
doi,
source: 'CrossRef',
paperInfo: info,
details: retracted ? {
...info,
reason,
notice_url: noticeUrl || work.URL || `https://doi.org/${doi}`,
} : null,
_references: (work.reference || [])
.map(r => r.DOI ? cleanDOI(r.DOI) : null)
.filter(Boolean),
_refCount: (work.reference || []).length,
};
}
} catch (e) {
console.warn('[RetractionChecker] CrossRef error:', e.message);
}
try {
await chrome.storage.local.set({ [cacheKey]: { result, timestamp: Date.now() } });
} catch (_) {}
return result;
}
// ─── Citation Scan ────────────────────────────────────────────────────
async function checkCitations(referenceDOIs, onProgress) {
const results = [];
const BATCH = 5;
const DELAY = 300;
for (let i = 0; i < referenceDOIs.length; i += BATCH) {
const batch = referenceDOIs.slice(i, i + BATCH);
const batchResults = await Promise.all(batch.map(doi => checkRetraction(doi)));
results.push(...batchResults);
onProgress(Math.min(results.length, referenceDOIs.length), referenceDOIs.length);
if (i + BATCH < referenceDOIs.length) {
await new Promise(r => setTimeout(r, DELAY));
}
}
return results;
}
// ─── Banner UI ────────────────────────────────────────────────────────
function injectStyles() {
if (document.getElementById('rc-styles')) return;
const style = document.createElement('style');
style.id = 'rc-styles';
style.textContent = `
@keyframes rcSlideIn {
from { transform:translateY(-100%); opacity:0; }
to { transform:translateY(0); opacity:1; }
}
@keyframes rcPulse { 0%,100%{opacity:1} 50%{opacity:0.5} }
#rc-banner * { box-sizing:border-box; }
#rc-banner a { color:#fde68a; text-decoration:underline; }
#rc-banner button:hover { opacity:0.8; }
.rc-cite-item {
background:rgba(0,0,0,0.25); border-radius:6px;
padding:8px 10px; margin-top:6px; font-size:11px; line-height:1.5;
}
.rc-progress-bar {
height:3px; background:rgba(255,255,255,0.15);
border-radius:2px; margin-top:8px; overflow:hidden;
}
.rc-progress-fill {
height:100%; background:rgba(255,255,255,0.5);
border-radius:2px; transition:width 0.3s ease;
}
`;
document.head.appendChild(style);
}
function removeBanners() {
document.getElementById('rc-banner')?.remove();
document.getElementById('rc-loading')?.remove();
}
function showLoadingBanner() {
removeBanners();
injectStyles();
const el = document.createElement('div');
el.id = 'rc-loading';
el.style.cssText = `
position:fixed;top:0;left:0;right:0;z-index:2147483647;
background:#1e3a5f;color:white;
font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;
font-size:13px;padding:10px 20px;text-align:center;
animation:rcPulse 1.5s ease-in-out infinite;
`;
el.textContent = '🔍 Checking retraction status…';
document.body.prepend(el);
}
function showMainBanner(result, citationSummary) {
removeBanners();
injectStyles();
const isRetracted = result.retracted;
const hasBadCitations = citationSummary?.retractedCount > 0;
const isScanning = citationSummary?.scanning;
const bg = isRetracted
? 'linear-gradient(135deg,#7f1d1d,#991b1b)'
: hasBadCitations
? 'linear-gradient(135deg,#78350f,#92400e)'
: 'linear-gradient(135deg,#14532d,#166534)';
const icon = isRetracted ? '⚠️' : hasBadCitations ? '🔶' : '✅';
const mainTitle = isRetracted
? 'RETRACTED PAPER'
: hasBadCitations
? `CITES ${citationSummary.retractedCount} RETRACTED PAPER${citationSummary.retractedCount > 1 ? 'S' : ''}`
: 'Paper Verified';
const mainSub = isRetracted
? (result.details?.reason || 'This paper has been retracted.')
: isScanning
? `Scanning ${citationSummary.total} citations for retractions…`
: citationSummary
? (hasBadCitations
? `Found in ${citationSummary.retractedCount} of ${citationSummary.checked} citations checked.`
: `No retractions found · ${citationSummary.checked} of ${citationSummary.total} citations checked`)
: 'No retraction notice found in CrossRef.';
// Retracted citations expandable list
let citesHTML = '';
if (hasBadCitations && citationSummary.retractedItems.length > 0) {
const items = citationSummary.retractedItems.map(r => `
<div class="rc-cite-item">
<strong>${r.paperInfo?.title || r.doi}</strong><br>
${r.paperInfo?.journal ? `📰 ${r.paperInfo.journal}` : ''}
${r.paperInfo?.year ? ` · ${r.paperInfo.year}` : ''}
${r.details?.notice_url
? ` · <a href="${r.details.notice_url}" target="_blank">View notice →</a>`
: ` · <a href="https://doi.org/${r.doi}" target="_blank">doi.org →</a>`}
<br><span style="opacity:0.6;font-size:10px;">${r.details?.reason || 'Retracted'}</span>
</div>`).join('');
citesHTML = `
<div id="rc-cites-panel" style="display:none;margin-top:8px;max-height:200px;overflow-y:auto;">${items}</div>
<button id="rc-toggle-btn" onclick="
var p=document.getElementById('rc-cites-panel');
var b=document.getElementById('rc-toggle-btn');
if(p.style.display==='none'){p.style.display='block';b.textContent='▲ Hide retracted citations';}
else{p.style.display='none';b.textContent='▼ Show '+${citationSummary.retractedCount}+' retracted citations';}
" style="margin-top:6px;background:rgba(255,255,255,0.15);border:1px solid rgba(255,255,255,0.3);
color:white;padding:4px 12px;border-radius:4px;cursor:pointer;font-size:11px;">
▼ Show ${citationSummary.retractedCount} retracted citation${citationSummary.retractedCount > 1 ? 's' : ''}
</button>`;
}
// Scanning progress bar
let progressHTML = '';
if (isScanning) {
const pct = citationSummary.total ? Math.round((citationSummary.checked / citationSummary.total) * 100) : 0;
progressHTML = `
<div class="rc-progress-bar"><div class="rc-progress-fill" id="rc-progress" style="width:${pct}%"></div></div>
<div style="font-size:10px;opacity:0.55;margin-top:3px;" id="rc-progress-label">
${citationSummary.checked} / ${citationSummary.total} citations checked
</div>`;
}
const info = result.details || result.paperInfo;
const banner = document.createElement('div');
banner.id = 'rc-banner';
banner.style.cssText = `
position:fixed;top:0;left:0;right:0;z-index:2147483647;
background:${bg};color:white;
font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;
box-shadow:0 4px 24px rgba(0,0,0,0.4);
animation:rcSlideIn 0.4s cubic-bezier(0.16,1,0.3,1);
`;
banner.innerHTML = `
<div style="max-width:960px;margin:0 auto;padding:12px 18px;display:flex;align-items:flex-start;gap:12px;">
<span style="font-size:22px;line-height:1;flex-shrink:0;margin-top:2px;">${icon}</span>
<div style="flex:1;min-width:0;">
<div style="font-weight:700;font-size:13px;letter-spacing:0.06em;text-transform:uppercase;">${mainTitle}</div>
<div style="font-size:12px;margin-top:2px;opacity:0.9;">${mainSub}</div>
${info?.title ? `<div style="font-size:11px;margin-top:5px;opacity:0.75;">
<strong>${info.title}</strong>
${info.journal ? ` · ${info.journal}` : ''}
${info.year ? ` · ${info.year}` : ''}
${result.details?.notice_url ? ` · <a href="${result.details.notice_url}" target="_blank">View retraction notice →</a>` : ''}
</div>` : ''}
${citesHTML}
${progressHTML}
<div style="font-size:10px;margin-top:6px;opacity:0.45;">DOI: ${result.doi} · Powered by CrossRef</div>
</div>
<button onclick="document.getElementById('rc-banner').remove()"
style="background:rgba(255,255,255,0.2);border:none;color:white;
width:26px;height:26px;border-radius:50%;cursor:pointer;font-size:14px;flex-shrink:0;">✕</button>
</div>`;
document.body.prepend(banner);
// Auto-dismiss clean banners
if (!isRetracted && !hasBadCitations && !isScanning) {
setTimeout(() => banner?.remove(), 7000);
}
}
function updateProgress(checked, total) {
const pct = Math.round((checked / total) * 100);
const fill = document.getElementById('rc-progress');
const label = document.getElementById('rc-progress-label');
if (fill) fill.style.width = `${pct}%`;
if (label) label.textContent = `${checked} / ${total} citations checked`;
}
// ─── Main ──────────────────────────────────────────────────────────────
async function run() {
const primaryDOI = extractPrimaryDOI();
if (!primaryDOI) return;
chrome.runtime.sendMessage({ type: 'DOI_FOUND', doi: primaryDOI });
showLoadingBanner();
// Step 1: Check the current paper
const result = await checkRetraction(primaryDOI);
const { alwaysShow } = await chrome.storage.local.get('alwaysShow');
const referenceDOIs = result._references || [];
const totalRefs = result._refCount || 0;
// Show banner after main check, before citation scan
const shouldShow = result.retracted || alwaysShow || referenceDOIs.length > 0;
if (shouldShow) {
showMainBanner(result, referenceDOIs.length > 0
? { scanning: true, checked: 0, total: referenceDOIs.length, retractedCount: 0, retractedItems: [] }
: null);
} else {
removeBanners();
}
chrome.runtime.sendMessage({ type: 'CHECK_RESULT', result, citationTotal: totalRefs });
// Step 2: Scan citations
if (referenceDOIs.length === 0) return;
const citationResults = await checkCitations(referenceDOIs, (checked, total) => {
updateProgress(checked, total);
});
const retractedCitations = citationResults.filter(r => r.retracted);
const citationSummary = {
scanning: false,
checked: citationResults.length,
total: totalRefs,
retractedCount: retractedCitations.length,
retractedItems: retractedCitations,
};
if (result.retracted || retractedCitations.length > 0 || alwaysShow) {
showMainBanner(result, citationSummary);
} else {
removeBanners();
}
chrome.runtime.sendMessage({ type: 'CITATION_RESULT', result, citationSummary });
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => setTimeout(run, 900));
} else {
setTimeout(run, 900);
}
})();