-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
511 lines (420 loc) · 11.4 KB
/
Copy pathcontent.js
File metadata and controls
511 lines (420 loc) · 11.4 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
let collectorActive = false;
let mutationObserver = null;
let scanTimer = null;
let scanInProgress = false;
let scanOptions = {
includeBackgrounds: true,
includeSrcset: true
};
const MIN_INITIAL_DELAY_MS = 500;
const MAX_INITIAL_DELAY_MS = 1000;
const MAX_SRCSET_SAMPLES = 300;
const MAX_BACKGROUND_SAMPLES = 300;
const DIMENSION_BATCH_SIZE = 12;
const BACKGROUND_ELEMENT_BATCH_SIZE = 120;
const MIN_SCAN_BATCH_DELAY_MS = 500;
const MAX_SCAN_BATCH_DELAY_MS = 1000;
sendRuntimeMessage({ type: "CONTENT_READY" }, (response) => {
if (!isRuntimeReady()) {
handleInvalidContext();
return;
}
const error = chrome.runtime.lastError;
if (error) {
handleRuntimeMessageError(error);
return;
}
if (response?.active) {
collectorActive = true;
updateScanOptions(response.scanOptions);
startCollector();
}
});
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type === "COLLECTOR_ACTIVE_CHANGED") {
collectorActive = Boolean(message.active);
updateScanOptions(message.scanOptions);
if (collectorActive) {
startCollector();
} else {
stopCollector();
}
sendResponse({ ok: true });
return false;
}
return false;
});
function startCollector() {
queueScan(randomInitialDelayMs());
if (!mutationObserver) {
mutationObserver = new MutationObserver(scheduleScan);
mutationObserver.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["src", "srcset", "style"]
});
}
document.addEventListener("load", scheduleScan, true);
window.addEventListener("scroll", scheduleScan, { passive: true });
window.addEventListener("resize", scheduleScan);
}
function stopCollector() {
collectorActive = false;
if (mutationObserver) {
mutationObserver.disconnect();
mutationObserver = null;
}
if (scanTimer) {
clearTimeout(scanTimer);
scanTimer = null;
}
document.removeEventListener("load", scheduleScan, true);
window.removeEventListener("scroll", scheduleScan);
window.removeEventListener("resize", scheduleScan);
}
function scheduleScan() {
queueScan(600);
}
function queueScan(delay) {
if (!collectorActive || scanTimer) {
return;
}
scanTimer = setTimeout(() => {
scanTimer = null;
scanPage().catch(handleScanError);
}, delay);
}
async function scanPage() {
if (!collectorActive || scanInProgress) {
return;
}
scanInProgress = true;
try {
const imageCandidates = [];
const srcsetCandidates = [];
const backgroundCandidates = [];
collectImageElements(imageCandidates);
sendCandidates(imageCandidates);
if (scanOptions.includeSrcset) {
await collectPictureSources(srcsetCandidates);
sendCandidates(srcsetCandidates);
}
if (scanOptions.includeBackgrounds) {
await collectBackgroundImages(backgroundCandidates);
sendCandidates(backgroundCandidates);
}
sendScanSummary({
images: imageCandidates.length,
srcset: srcsetCandidates.length,
backgrounds: backgroundCandidates.length
});
} finally {
scanInProgress = false;
}
}
function sendScanSummary(summary) {
if (!collectorActive) {
return;
}
sendRuntimeMessage({
type: "SCAN_SUMMARY",
...summary
});
}
function sendCandidates(candidates) {
if (!collectorActive || candidates.length === 0) {
return;
}
sendRuntimeMessage({
type: "IMAGE_CANDIDATES",
candidates
});
}
function collectImageElements(candidates) {
for (const image of document.images) {
if (!isVisibleInViewport(image)) {
continue;
}
const url = image.currentSrc || image.src;
pushCandidate(candidates, url, image.naturalWidth, image.naturalHeight, "image");
}
}
async function collectPictureSources(candidates) {
const sourceElements = document.querySelectorAll("source[srcset], img[srcset]");
const visibleSources = new Map();
for (const element of sourceElements) {
const visibleElement = getVisibleSrcsetElement(element);
if (!visibleElement) {
continue;
}
const currentUrl = visibleElement.currentSrc || visibleElement.src;
for (const item of parseSrcset(element.getAttribute("srcset"))) {
const url = toAbsoluteUrl(item);
if (url && toAbsoluteUrl(currentUrl) === url) {
visibleSources.set(url, {
width: visibleElement.naturalWidth,
height: visibleElement.naturalHeight
});
}
}
}
for (const [url, dimensions] of Array.from(visibleSources).slice(0, MAX_SRCSET_SAMPLES)) {
pushCandidate(candidates, url, dimensions.width, dimensions.height, "srcset");
}
}
async function collectBackgroundImages(candidates) {
const elements = Array.from(document.querySelectorAll("*"));
const urls = new Set();
for (let index = 0; index < elements.length && collectorActive; index += BACKGROUND_ELEMENT_BATCH_SIZE) {
const batch = elements.slice(index, index + BACKGROUND_ELEMENT_BATCH_SIZE);
for (const element of batch) {
if (!isVisibleInViewport(element)) {
continue;
}
const background = getComputedStyle(element).backgroundImage;
for (const url of extractCssUrls(background)) {
urls.add(url);
}
}
if (index + BACKGROUND_ELEMENT_BATCH_SIZE < elements.length) {
await sleep(randomScanBatchDelayMs());
}
}
const samples = Array.from(urls).slice(0, MAX_BACKGROUND_SAMPLES);
const dimensions = await loadDimensionsInBatches(samples);
dimensions.forEach((result) => {
if (result) {
pushCandidate(candidates, result.url, result.width, result.height, "background");
}
});
}
function getVisibleSrcsetElement(element) {
if (element instanceof HTMLImageElement) {
return isVisibleInViewport(element) ? element : null;
}
const image = element.parentElement?.querySelector("img");
return image && isVisibleInViewport(image) ? image : null;
}
function isVisibleInViewport(element) {
if (!(element instanceof Element)) {
return false;
}
const style = getComputedStyle(element);
if (
style.display === "none" ||
style.visibility === "hidden" ||
style.visibility === "collapse" ||
hasInvisibleAncestor(element)
) {
return false;
}
const rects = Array.from(element.getClientRects());
if (rects.length === 0) {
return false;
}
return rects.some((rect) => (
rect.width > 0 &&
rect.height > 0 &&
rect.bottom > 0 &&
rect.right > 0 &&
rect.top < window.innerHeight &&
rect.left < window.innerWidth
));
}
function hasInvisibleAncestor(element) {
let current = element;
while (current && current instanceof Element) {
const style = getComputedStyle(current);
if (
style.display === "none" ||
style.visibility === "hidden" ||
style.visibility === "collapse" ||
Number(style.opacity) === 0
) {
return true;
}
current = current.parentElement;
}
return false;
}
function pushCandidate(candidates, rawUrl, width, height, source) {
const url = toAbsoluteUrl(rawUrl);
if (!url) {
return;
}
candidates.push({
url,
width: Number(width) || 0,
height: Number(height) || 0,
source
});
}
function toAbsoluteUrl(rawUrl) {
if (!rawUrl || typeof rawUrl !== "string") {
return null;
}
const trimmed = rawUrl.trim();
if (!trimmed || trimmed.startsWith("data:") || trimmed.startsWith("blob:")) {
return null;
}
try {
return new URL(trimmed, document.baseURI).href;
} catch (_) {
return null;
}
}
function parseSrcset(srcset) {
if (!srcset) {
return [];
}
return splitSrcsetCandidates(srcset)
.map(parseSrcsetUrl)
.filter(Boolean);
}
function splitSrcsetCandidates(srcset) {
const candidates = [];
let current = "";
let quote = "";
let parenDepth = 0;
for (const char of srcset) {
if (quote) {
current += char;
if (char === quote) {
quote = "";
}
continue;
}
if (char === "\"" || char === "'") {
quote = char;
current += char;
continue;
}
if (char === "(") {
parenDepth += 1;
current += char;
continue;
}
if (char === ")" && parenDepth > 0) {
parenDepth -= 1;
current += char;
continue;
}
if (char === "," && parenDepth === 0) {
if (current.trim()) {
candidates.push(current.trim());
}
current = "";
continue;
}
current += char;
}
if (current.trim()) {
candidates.push(current.trim());
}
return candidates;
}
function parseSrcsetUrl(candidate) {
const trimmed = candidate.trim();
if (!trimmed) {
return "";
}
const quoted = trimmed.match(/^(['"])(.*?)\1(?:\s|$)/);
if (quoted) {
return quoted[2];
}
const match = trimmed.match(/^(\S+)/);
return match ? match[1] : "";
}
function extractCssUrls(value) {
const urls = [];
const pattern = /url\((?:"([^"]+)"|'([^']+)'|([^'")]+))\)/g;
let match;
while ((match = pattern.exec(value || "")) !== null) {
urls.push(match[1] || match[2] || match[3]);
}
return urls;
}
function loadImageDimensions(url) {
return new Promise((resolve) => {
const image = new Image();
image.decoding = "async";
image.onload = () => resolve({
url: image.currentSrc || url,
width: image.naturalWidth,
height: image.naturalHeight
});
image.onerror = () => resolve(null);
image.src = url;
});
}
async function loadDimensionsInBatches(urls) {
const results = [];
for (let index = 0; index < urls.length && collectorActive; index += DIMENSION_BATCH_SIZE) {
const batch = urls.slice(index, index + DIMENSION_BATCH_SIZE);
results.push(...await Promise.all(batch.map(loadImageDimensions)));
if (index + DIMENSION_BATCH_SIZE < urls.length) {
await sleep(randomScanBatchDelayMs());
}
}
return results;
}
function updateScanOptions(nextOptions) {
if (!nextOptions) {
return;
}
scanOptions = {
includeBackgrounds: nextOptions.includeBackgrounds !== false,
includeSrcset: nextOptions.includeSrcset !== false
};
}
function randomInitialDelayMs() {
return Math.floor(MIN_INITIAL_DELAY_MS + Math.random() * (MAX_INITIAL_DELAY_MS - MIN_INITIAL_DELAY_MS + 1));
}
function randomScanBatchDelayMs() {
return Math.floor(MIN_SCAN_BATCH_DELAY_MS + Math.random() * (MAX_SCAN_BATCH_DELAY_MS - MIN_SCAN_BATCH_DELAY_MS + 1));
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function sendRuntimeMessage(message, callback) {
if (!isRuntimeReady()) {
handleInvalidContext();
return false;
}
try {
const result = chrome.runtime.sendMessage(message, callback);
if (result && typeof result.catch === "function") {
result.catch(handleRuntimeMessageError);
}
return true;
} catch (error) {
handleRuntimeMessageError(error);
return false;
}
}
function isRuntimeReady() {
try {
return Boolean(chrome?.runtime?.id);
} catch (_) {
return false;
}
}
function handleScanError(error) {
handleRuntimeMessageError(error);
}
function handleRuntimeMessageError(error) {
const message = error?.message || "";
if (
message.includes("Extension context invalidated") ||
message.includes("Extension context was invalidated") ||
message.includes("Receiving end does not exist")
) {
handleInvalidContext();
return;
}
console.warn("Jjal Collector content script error:", error);
}
function handleInvalidContext() {
stopCollector();
}