forked from omkarrr2533/chrome-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
193 lines (161 loc) · 6.88 KB
/
background.js
File metadata and controls
193 lines (161 loc) · 6.88 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
/**
* SatyaCheck — Background Service Worker
* सत्य की जाँच | India's AI Fake News Detector
*
* Runs as a Manifest V3 background service worker.
* Responsibilities:
* 1. Badge management — shows ✓/! icon on suspicious pages
* 2. Tab tracking — remembers analysis results per tab
* 3. Context menu — right-click "Check with SatyaCheck"
* 4. Backend health check on startup
* 5. Extension install/update handler
*
* File: dist/background.js
*/
'use strict';
// ─── Configuration ─────────────────────────────────────────────────────────────
const BACKEND_URL = 'http://localhost:8000';
const VERSION = '2.1.0';
// ─── Tab Result Store ──────────────────────────────────────────────────────────
// Stores the last analysis result for each tab (by tab ID)
const tabResults = new Map();
// ─── Install / Update Handler ──────────────────────────────────────────────────
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === 'install') {
console.log(`[SatyaCheck] v${VERSION} installed — सत्य की जाँच`);
// Set default settings on install
chrome.storage.sync.set({
autoScan: false,
alertOnFake: true,
checkImages: true,
checkSources: true,
sensitivity: 'strict',
language: 'english',
backendUrl: BACKEND_URL,
installedAt: new Date().toISOString(),
});
// Open welcome/setup tab
chrome.tabs.create({
url: chrome.runtime.getURL('index.html'),
});
}
if (details.reason === 'update') {
console.log(`[SatyaCheck] Updated to v${VERSION}`);
}
// Create right-click context menu
chrome.contextMenus.create({
id: 'satyacheck-check',
title: '🔍 Check with SatyaCheck',
contexts: ['page', 'selection'],
});
});
// ─── Context Menu Handler ─────────────────────────────────────────────────────
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'satyacheck-check') {
// Open the popup (can't programmatically open popup in MV3, so open in new tab)
chrome.tabs.create({
url: chrome.runtime.getURL('index.html') + '?tab=' + tab.id,
});
}
});
// ─── Message Handler ─────────────────────────────────────────────────────────
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// Store analysis result for a tab
if (message.action === 'storeResult') {
const tabId = sender.tab?.id || message.tabId;
if (tabId) {
tabResults.set(tabId, {
result: message.result,
timestamp: Date.now(),
});
// Update badge
updateBadge(tabId, message.result?.layer4?.overallRisk || message.result?.layer4?.overall_risk);
}
sendResponse({ success: true });
return true;
}
// Get stored result for a tab
if (message.action === 'getResult') {
const tabId = message.tabId;
const stored = tabResults.get(tabId);
sendResponse({ result: stored?.result || null });
return true;
}
// Page info from content script
if (message.action === 'pageInfo') {
const tabId = sender.tab?.id;
if (tabId && message.isArticle) {
// Show a subtle badge indicating the page can be checked
chrome.action.setBadgeText({ text: '?', tabId });
chrome.action.setBadgeBackgroundColor({ color: '#64748b', tabId });
chrome.action.setBadgeTextColor({ color: '#ffffff', tabId });
}
return true;
}
// Backend health check
if (message.action === 'checkBackend') {
checkBackendHealth()
.then(status => sendResponse({ status }))
.catch(() => sendResponse({ status: 'offline' }));
return true; // async
}
// Clear badge for tab
if (message.action === 'clearBadge') {
const tabId = sender.tab?.id || message.tabId;
if (tabId) {
chrome.action.setBadgeText({ text: '', tabId });
}
sendResponse({ success: true });
return true;
}
});
// ─── Tab Close Handler ─────────────────────────────────────────────────────────
chrome.tabs.onRemoved.addListener((tabId) => {
tabResults.delete(tabId);
});
// ─── Badge Management ──────────────────────────────────────────────────────────
/**
* Update the extension icon badge based on analysis result.
* @param {number} tabId
* @param {string} riskLevel - TRUSTWORTHY / BE CAREFUL / MISLEADING / FAKE NEWS
*/
function updateBadge(tabId, riskLevel) {
if (!tabId || !riskLevel) return;
const badgeConfig = {
'TRUSTWORTHY': { text: '✓', color: '#10b981' }, // Green
'BE CAREFUL': { text: '!', color: '#f59e0b' }, // Amber
'MISLEADING': { text: '!!', color: '#f97316' }, // Orange
'FAKE NEWS': { text: '✕', color: '#ef4444' }, // Red
};
const config = badgeConfig[riskLevel] || { text: '?', color: '#64748b' };
chrome.action.setBadgeText({ text: config.text, tabId });
chrome.action.setBadgeBackgroundColor({ color: config.color, tabId });
chrome.action.setBadgeTextColor({ color: '#ffffff', tabId });
}
// ─── Backend Health Check ─────────────────────────────────────────────────────
/**
* Check if the SatyaCheck backend is running and reachable.
* @returns {Promise<string>} 'online' | 'offline' | 'error'
*/
async function checkBackendHealth() {
try {
const settings = await chrome.storage.sync.get(['backendUrl']);
const url = settings.backendUrl || BACKEND_URL;
const response = await fetch(`${url}/health/ping`, {
method: 'GET',
signal: AbortSignal.timeout(5000), // 5 second timeout
});
if (response.ok) {
return 'online';
}
return 'error';
} catch (error) {
console.warn('[SatyaCheck] Backend unreachable:', error.message);
return 'offline';
}
}
// ─── Startup Health Check ─────────────────────────────────────────────────────
// Check backend health when service worker starts
checkBackendHealth().then(status => {
console.log(`[SatyaCheck] Backend status on startup: ${status}`);
}).catch(() => {});