-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
399 lines (339 loc) · 11 KB
/
background.js
File metadata and controls
399 lines (339 loc) · 11 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
// Background script for Link Fetch extension
// Helper to normalize URLs for consistent storage/deduplication
function normalizeLink(url) {
if (typeof url !== 'string') {
return '';
}
const trimmed = url.trim();
if (!trimmed) {
return '';
}
try {
const parsed = new URL(trimmed);
if (!parsed.protocol.startsWith('http')) {
return trimmed;
}
parsed.hostname = parsed.hostname.toLowerCase();
let pathname = parsed.pathname || '/';
if (pathname.length > 1) {
pathname = pathname.replace(/\/+$/, '');
if (!pathname) {
pathname = '/';
}
}
return `${parsed.protocol}//${parsed.host}${pathname}${parsed.search}${parsed.hash}`;
} catch (e) {
return trimmed.replace(/\s+/g, '');
}
}
function normalizeStoredData(links = [], timestamps = {}) {
const normalizedLinks = [];
const normalizedTimestamps = {};
const seen = new Set();
let changed = false;
const originalLinkCount = Array.isArray(links) ? links.length : 0;
links.forEach(original => {
if (typeof original !== 'string') {
changed = true;
return;
}
const normalized = normalizeLink(original);
if (normalized !== original) {
changed = true;
}
if (!normalized) {
changed = true;
return;
}
if (!seen.has(normalized)) {
seen.add(normalized);
normalizedLinks.push(normalized);
} else {
changed = true;
}
const keysToCheck = [original, normalized];
keysToCheck.forEach(key => {
if (timestamps && Object.prototype.hasOwnProperty.call(timestamps, key)) {
const value = timestamps[key];
if (value !== undefined) {
if (!Object.prototype.hasOwnProperty.call(normalizedTimestamps, normalized) || value > normalizedTimestamps[normalized]) {
normalizedTimestamps[normalized] = value;
}
}
if (key !== normalized) {
changed = true;
}
}
});
});
if (timestamps) {
const originalKeys = Object.keys(timestamps).filter(key => typeof key === 'string');
if (originalKeys.length !== Object.keys(normalizedTimestamps).length) {
changed = true;
}
}
if (changed) {
const duplicatesRemoved = originalLinkCount - normalizedLinks.length;
console.info('[Link Fetch] Normalized stored data', {
linksBefore: originalLinkCount,
linksAfter: normalizedLinks.length,
duplicatesRemoved: duplicatesRemoved > 0 ? duplicatesRemoved : 0
});
}
return { links: normalizedLinks, timestamps: normalizedTimestamps, changed };
}
// Set up context menu
chrome.runtime.onInstalled.addListener(() => {
// Create main context menu item
chrome.contextMenus.create({
id: "fetchLinkUnderCursor",
title: "Add to Link Fetch",
contexts: ["link"]
});
// Create context menu for the page
chrome.contextMenus.create({
id: "fetchAllLinks",
title: "Fetch All Links on This Page",
contexts: ["page"]
});
// Create sub-menu for selection
chrome.contextMenus.create({
id: "fetchLinkInSelection",
title: "Extract Links from Selection",
contexts: ["selection"]
});
// Show the number of stored links in the badge
updateBadge();
});
// Handle context menu clicks
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "fetchLinkUnderCursor" && info.linkUrl) {
// Store the link in local storage
addLink(info.linkUrl);
// Show visual feedback - blink the badge
blinkBadge();
}
else if (info.menuItemId === "fetchAllLinks") {
// Ask content script to get all links via messaging (avoids duplicate logic)
chrome.tabs.sendMessage(tab.id, { action: "getLinks" }, (response) => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
return;
}
const links = (response && response.links) ? response.links : [];
if (links.length > 0) {
// Add all links to storage
addLinks(links);
// Show visual feedback - blink the badge
blinkBadge();
// Show notification with count
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon128.png',
title: 'Link Fetch',
message: `Added ${links.length} links from the page`
});
}
});
}
else if (info.menuItemId === "fetchLinkInSelection") {
// Ask content script to extract links from selection via messaging
chrome.tabs.sendMessage(tab.id, { action: "getLinksFromSelection" }, (response) => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
return;
}
const links = (response && response.links) ? response.links : [];
if (links.length > 0) {
// Add all links to storage
addLinks(links);
// Show visual feedback - blink the badge
blinkBadge();
}
});
}
// Remove side panel context menu handler
});
// Function to add a single link
function addLink(url) {
chrome.storage.local.get(['links', 'linkTimestamps'], function(result) {
const normalizedData = normalizeStoredData(result.links || [], result.linkTimestamps || {});
const normalizedUrl = normalizeLink(url);
if (!normalizedUrl) {
return;
}
let links = normalizedData.links;
let timestamps = normalizedData.timestamps;
let shouldPersist = normalizedData.changed;
if (!links.includes(normalizedUrl)) {
links.push(normalizedUrl);
timestamps[normalizedUrl] = Date.now();
shouldPersist = true;
}
if (shouldPersist) {
chrome.storage.local.set({
'links': links,
'linkTimestamps': timestamps
}, function() {
updateBadge();
});
} else {
updateBadge();
}
});
}
// Function to add multiple links
function addLinks(newLinks) {
if (!Array.isArray(newLinks) || newLinks.length === 0) return;
chrome.storage.local.get(['links', 'linkTimestamps'], function(result) {
const normalizedData = normalizeStoredData(result.links || [], result.linkTimestamps || {});
let links = normalizedData.links;
let timestamps = normalizedData.timestamps;
let shouldPersist = normalizedData.changed;
const now = Date.now();
newLinks.forEach(url => {
const normalizedUrl = normalizeLink(url);
if (!normalizedUrl) {
shouldPersist = true;
return;
}
if (!links.includes(normalizedUrl)) {
links.push(normalizedUrl);
timestamps[normalizedUrl] = now;
shouldPersist = true;
}
});
if (shouldPersist) {
chrome.storage.local.set({
'links': links,
'linkTimestamps': timestamps
}, function() {
updateBadge();
});
} else {
updateBadge();
}
});
}
// Update badge with count of links
function updateBadge() {
chrome.storage.local.get(['links', 'linkTimestamps'], function(result) {
const normalizedData = normalizeStoredData(result.links || [], result.linkTimestamps || {});
const finalizeBadge = () => {
const count = normalizedData.links.length;
if (count > 0) {
chrome.action.setBadgeText({ text: count.toString() });
chrome.action.setBadgeBackgroundColor({ color: '#1a73e8' });
} else {
chrome.action.setBadgeText({ text: '' });
}
};
if (normalizedData.changed) {
chrome.storage.local.set({
'links': normalizedData.links,
'linkTimestamps': normalizedData.timestamps
}, finalizeBadge);
} else {
finalizeBadge();
}
});
}
// Blink the badge for visual feedback
function blinkBadge() {
chrome.action.setBadgeBackgroundColor({ color: '#34a853' });
setTimeout(() => {
chrome.action.setBadgeBackgroundColor({ color: '#1a73e8' });
}, 1000);
}
// Listen for messages from popup or content scripts
chrome.runtime.onMessage.addListener(
function(request, _sender, sendResponse) {
if (request.action === "fetchLinks") {
// Send message to content script to get links
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.sendMessage(
tabs[0].id,
{ action: "getLinks" },
function(response) {
if (chrome.runtime.lastError) {
sendResponse({ success: false, error: chrome.runtime.lastError.message });
return;
}
if (response && response.links) {
sendResponse({ success: true, links: response.links });
} else {
sendResponse({ success: false, error: "No links received" });
}
}
);
});
return true; // Keep the message channel open for async response
}
else if (request.action === "updateBadge") {
updateBadge();
sendResponse({ success: true });
}
// Remove openSidePanel message handler
else if (request.action === "checkLinks") {
// Check if the links are valid/broken
if (request.links && request.links.length > 0) {
checkLinks(request.links)
.then(results => {
sendResponse({ success: true, results: results });
})
.catch(error => {
console.error('Error checking links:', error);
sendResponse({ success: false, error: error.message });
});
return true; // Keep the message channel open for async response
}
}
}
);
// Function to check if links are working or broken
async function checkLinks(links) {
const results = {};
// Check links in batches to avoid overwhelming the browser
const batchSize = 5;
const batches = [];
// Split the links array into batches
for (let i = 0; i < links.length; i += batchSize) {
batches.push(links.slice(i, i + batchSize));
}
// Process each batch sequentially
for (const batch of batches) {
// Process links in this batch in parallel
await Promise.all(
batch.map(async (link) => {
try {
// Use fetch with a timeout to check if the link is valid
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout
// Try HEAD first with proper host permissions; fall back to GET if needed
const response = await fetch(link, {
method: 'HEAD',
cache: 'no-store',
redirect: 'follow',
signal: controller.signal
}).catch(() => null);
let ok = !!(response && response.ok);
if (!ok) {
const response2 = await fetch(link, {
method: 'GET',
cache: 'no-store',
redirect: 'follow',
signal: controller.signal
}).catch(() => null);
ok = !!(response2 && response2.ok);
}
clearTimeout(timeoutId);
results[link] = ok;
} catch (error) {
// If there's an error (network, CORS, timeout), consider the link broken
results[link] = false;
}
})
);
}
return results;
}