-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
691 lines (601 loc) · 22.4 KB
/
content.js
File metadata and controls
691 lines (601 loc) · 22.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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
// Content script for PerfectParallel extension
let comparisonOverlay = null;
let isComparing = false;
// Listen for messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
try {
if (request.action === "startComparison") {
startComparison(request.uploadedImage, request.sensitivity)
.then((result) => {
sendResponse(result);
})
.catch((error) => {
console.error("startComparison error:", error);
let errorMessage;
if (error === null) {
errorMessage = "Comparison failed: null error";
} else if (error === undefined) {
errorMessage = "Comparison failed: undefined error";
} else if (typeof error === "string") {
errorMessage = error;
} else if (error?.message) {
errorMessage = error.message;
} else if (error?.toString && typeof error.toString === "function") {
errorMessage = error.toString();
} else {
errorMessage = "Unknown comparison error";
}
sendResponse({
success: false,
error: errorMessage,
});
});
return true; // Keep message channel open for async response
} else if (request.action === "clearComparison") {
clearComparison();
sendResponse({ success: true });
} else if (request.action === "hideHighlights") {
const highlights = document.querySelectorAll(".pp-page-highlight");
highlights.forEach((highlight) => (highlight.style.display = "none"));
sendResponse({ success: true });
} else if (request.action === "showHighlights") {
const highlights = document.querySelectorAll(".pp-page-highlight");
highlights.forEach((highlight) => (highlight.style.display = "block"));
sendResponse({ success: true });
} else if (request.action === "ping") {
sendResponse({ success: true });
} else {
sendResponse({
success: false,
error: "Unknown action: " + request.action,
});
}
} catch (error) {
console.error("Message handler error:", error);
sendResponse({
success: false,
error: error?.message || "Message handler failed",
});
}
});
async function startComparison(uploadedImageData, sensitivity) {
try {
if (isComparing)
return { success: false, error: "Comparison already in progress" };
isComparing = true;
// Capture full page instead of just viewport
const currentPageData = await captureFullPage();
// Create overlay for comparison
createComparisonOverlay();
// Compare images
const comparisonResult = await compareImages(
uploadedImageData,
currentPageData,
sensitivity
);
// Check if comparison was successful
if (comparisonResult.success === false) {
isComparing = false;
return comparisonResult; // Return the error from compareImages
}
// Show results in overlay
showComparisonResults(comparisonResult);
isComparing = false;
return {
success: true,
similarity: comparisonResult.similarity,
differences: comparisonResult.differences,
totalPixels: comparisonResult.totalPixels,
};
} catch (error) {
console.error("Error in startComparison:", error);
isComparing = false;
return {
success: false,
error: error?.message || error?.toString() || "Unknown comparison error",
};
}
}
// Function to capture the full page using native browser APIs
async function captureFullPage() {
return new Promise(async (resolve, reject) => {
try {
// Get the full page dimensions
const scrollHeight = Math.max(
document.body.scrollHeight,
document.body.offsetHeight,
document.documentElement.clientHeight,
document.documentElement.scrollHeight,
document.documentElement.offsetHeight
);
const scrollWidth = Math.max(
document.body.scrollWidth,
document.body.offsetWidth,
document.documentElement.clientWidth,
document.documentElement.scrollWidth,
document.documentElement.offsetWidth
);
// For now, use a simple approach: create a canvas and draw the page
// This is a simplified version - for better results, consider using html2canvas library
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// Set canvas size to full page
canvas.width = scrollWidth;
canvas.height = scrollHeight;
// Create an image from the page content using dom-to-image approach
const svgString = createSVGFromPage(scrollWidth, scrollHeight);
const img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL("image/png");
resolve(dataURL);
};
img.onerror = function (event) {
// Fallback to viewport capture
chrome.runtime.sendMessage({ action: "captureTab" }, (response) => {
if (chrome.runtime.lastError) {
reject(
new Error(
`Chrome runtime error: ${chrome.runtime.lastError.message}`
)
);
} else if (response && response.error) {
reject(new Error(response.error));
} else if (response && response.screenshot) {
resolve(response.screenshot);
} else {
reject(new Error("Failed to capture screenshot"));
}
});
};
img.src =
"data:image/svg+xml;charset=utf-8," + encodeURIComponent(svgString);
} catch (error) {
// Fallback to viewport capture
chrome.runtime.sendMessage({ action: "captureTab" }, (response) => {
if (chrome.runtime.lastError) {
reject(
new Error(
`Chrome runtime error: ${chrome.runtime.lastError.message}`
)
);
} else if (response && response.error) {
reject(new Error(response.error));
} else if (response && response.screenshot) {
resolve(response.screenshot);
} else {
reject(new Error("Failed to capture screenshot"));
}
});
}
});
}
// Helper function to create SVG from page content
function createSVGFromPage(width, height) {
try {
// Get all stylesheets
let styles = "";
for (let i = 0; i < document.styleSheets.length; i++) {
try {
const styleSheet = document.styleSheets[i];
if (styleSheet.cssRules) {
for (let j = 0; j < styleSheet.cssRules.length; j++) {
styles += styleSheet.cssRules[j].cssText + "\n";
}
}
} catch (e) {
// Skip cross-origin stylesheets
}
}
// Clone the document body
const clonedBody = document.body
? document.body.cloneNode(true)
: document.createElement("div");
// Remove any existing highlights
const existingHighlights =
clonedBody.querySelectorAll(".pp-page-highlight");
existingHighlights.forEach((highlight) => highlight.remove());
// Remove the comparison overlay
const overlay = clonedBody.querySelector("#perfectparallel-overlay");
if (overlay) overlay.remove();
const svgString = `
<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">
<defs>
<style type="text/css">
<![CDATA[
${styles}
]]>
</style>
</defs>
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
${clonedBody.outerHTML}
</div>
</foreignObject>
</svg>
`;
return svgString;
} catch (error) {
throw new Error("Failed to create SVG representation of page");
}
}
function createComparisonOverlay() {
if (comparisonOverlay) {
comparisonOverlay.remove();
}
comparisonOverlay = document.createElement("div");
comparisonOverlay.id = "perfectparallel-overlay";
comparisonOverlay.innerHTML = `
<div class="pp-overlay-header">
<h3>PerfectParallel Comparison</h3>
<button class="pp-close-btn" onclick="this.closest('#perfectparallel-overlay').remove()">×</button>
</div>
<div class="pp-overlay-content">
<div class="pp-images-container">
<div class="pp-image-section">
<h4>Uploaded Screenshot</h4>
<canvas id="pp-uploaded-canvas"></canvas>
</div>
<div class="pp-image-section">
<h4>Current Page</h4>
<canvas id="pp-current-canvas"></canvas>
</div>
<div class="pp-image-section">
<h4>Differences</h4>
<canvas id="pp-diff-canvas"></canvas>
</div>
</div>
<div class="pp-stats">
<div class="pp-similarity">Similarity: <span id="pp-similarity-value">Calculating...</span></div>
<div class="pp-differences">Differences found: <span id="pp-diff-count">Calculating...</span></div>
</div>
</div>
`;
document.body.appendChild(comparisonOverlay);
}
async function compareImages(uploadedImageData, currentPageData, sensitivity) {
return new Promise((resolve) => {
const uploadedImg = new Image();
const currentImg = new Image();
let imagesLoaded = 0;
const onImageLoad = () => {
imagesLoaded++;
if (imagesLoaded === 2) {
// Use setTimeout to prevent blocking the UI
setTimeout(performComparison, 100);
}
};
uploadedImg.onload = onImageLoad;
currentImg.onload = onImageLoad;
uploadedImg.src = uploadedImageData;
currentImg.src = currentPageData;
function performComparison() {
try {
const uploadedCanvas = document.getElementById("pp-uploaded-canvas");
const currentCanvas = document.getElementById("pp-current-canvas");
const diffCanvas = document.getElementById("pp-diff-canvas");
if (!uploadedCanvas || !currentCanvas || !diffCanvas) {
resolve({ success: false, error: "Canvas elements not found" });
return;
}
// Calculate display dimensions for each image separately to maintain aspect ratios
const maxDisplayWidth = 300;
const maxDisplayHeight = 200;
// Calculate uploaded image display size
const uploadedAspect = uploadedImg.width / uploadedImg.height;
let uploadedDisplayWidth, uploadedDisplayHeight;
if (uploadedAspect > maxDisplayWidth / maxDisplayHeight) {
uploadedDisplayWidth = maxDisplayWidth;
uploadedDisplayHeight = maxDisplayWidth / uploadedAspect;
} else {
uploadedDisplayHeight = maxDisplayHeight;
uploadedDisplayWidth = maxDisplayHeight * uploadedAspect;
}
// Calculate current image display size
const currentAspect = currentImg.width / currentImg.height;
let currentDisplayWidth, currentDisplayHeight;
if (currentAspect > maxDisplayWidth / maxDisplayHeight) {
currentDisplayWidth = maxDisplayWidth;
currentDisplayHeight = maxDisplayWidth / currentAspect;
} else {
currentDisplayHeight = maxDisplayHeight;
currentDisplayWidth = maxDisplayHeight * currentAspect;
}
// Use the larger display dimensions for diff canvas to show both properly
const diffDisplayWidth = Math.max(
uploadedDisplayWidth,
currentDisplayWidth
);
const diffDisplayHeight = Math.max(
uploadedDisplayHeight,
currentDisplayHeight
);
// Set canvas dimensions individually to maintain proper aspect ratios
uploadedCanvas.width = uploadedDisplayWidth;
uploadedCanvas.height = uploadedDisplayHeight;
currentCanvas.width = currentDisplayWidth;
currentCanvas.height = currentDisplayHeight;
diffCanvas.width = diffDisplayWidth;
diffCanvas.height = diffDisplayHeight;
const uploadedCtx = uploadedCanvas.getContext("2d");
const currentCtx = currentCanvas.getContext("2d");
const diffCtx = diffCanvas.getContext("2d");
// Draw images maintaining their individual aspect ratios for display
uploadedCtx.drawImage(
uploadedImg,
0,
0,
uploadedDisplayWidth,
uploadedDisplayHeight
);
currentCtx.drawImage(
currentImg,
0,
0,
currentDisplayWidth,
currentDisplayHeight
);
// For comparison, we need to normalize to the same dimensions
// Use the smaller image dimensions to avoid stretching, but scale appropriately
const maxComparisonSize = 800;
let comparisonWidth = Math.min(uploadedImg.width, currentImg.width);
let comparisonHeight = Math.min(uploadedImg.height, currentImg.height);
// Scale down if too large
if (
comparisonWidth > maxComparisonSize ||
comparisonHeight > maxComparisonSize
) {
const scale = Math.min(
maxComparisonSize / comparisonWidth,
maxComparisonSize / comparisonHeight
);
comparisonWidth = Math.floor(comparisonWidth * scale);
comparisonHeight = Math.floor(comparisonHeight * scale);
}
// Create comparison canvases at normalized size
const comparisonCanvas1 = document.createElement("canvas");
const comparisonCanvas2 = document.createElement("canvas");
comparisonCanvas1.width = comparisonCanvas2.width = comparisonWidth;
comparisonCanvas1.height = comparisonCanvas2.height = comparisonHeight;
const ctx1 = comparisonCanvas1.getContext("2d");
const ctx2 = comparisonCanvas2.getContext("2d");
// Draw images at normalized comparison size (this may involve some stretching for accurate comparison)
ctx1.drawImage(uploadedImg, 0, 0, comparisonWidth, comparisonHeight);
ctx2.drawImage(currentImg, 0, 0, comparisonWidth, comparisonHeight);
// Get image data for comparison at normalized size
const uploadedData = ctx1.getImageData(
0,
0,
comparisonWidth,
comparisonHeight
);
const currentData = ctx2.getImageData(
0,
0,
comparisonWidth,
comparisonHeight
);
const diffData = diffCtx.createImageData(
diffDisplayWidth,
diffDisplayHeight
);
// Perform optimized pixel-by-pixel comparison
let totalPixels = comparisonWidth * comparisonHeight;
let differentPixels = 0;
let differenceRegions = [];
const threshold = (11 - sensitivity) * 10;
// Sample pixels instead of checking every single one for performance
const sampleRate = Math.max(
1,
Math.floor(Math.sqrt(totalPixels) / 100)
); // Dynamic sampling
for (let y = 0; y < comparisonHeight; y += sampleRate) {
for (let x = 0; x < comparisonWidth; x += sampleRate) {
const i = (y * comparisonWidth + x) * 4;
const r1 = uploadedData.data[i];
const g1 = uploadedData.data[i + 1];
const b1 = uploadedData.data[i + 2];
const r2 = currentData.data[i];
const g2 = currentData.data[i + 1];
const b2 = currentData.data[i + 2];
const rDiff = Math.abs(r1 - r2);
const gDiff = Math.abs(g1 - g2);
const bDiff = Math.abs(b1 - b2);
const totalDiff = rDiff + gDiff + bDiff;
if (totalDiff > threshold) {
differentPixels++;
// Only create regions for significant differences, not every pixel
if (differenceRegions.length < 1000) {
// Limit regions for performance
differenceRegions.push({
x: x,
y: y,
width: sampleRate,
height: sampleRate,
});
}
// Draw difference on display canvas
const displayX = Math.floor(
(x / comparisonWidth) * diffDisplayWidth
);
const displayY = Math.floor(
(y / comparisonHeight) * diffDisplayHeight
);
const displayI = (displayY * diffDisplayWidth + displayX) * 4;
if (displayI < diffData.data.length) {
diffData.data[displayI] = 255; // R
diffData.data[displayI + 1] = 0; // G
diffData.data[displayI + 2] = 0; // B
diffData.data[displayI + 3] = 180; // A
}
}
}
}
diffCtx.putImageData(diffData, 0, 0);
// Adjust similarity calculation for sampling
const sampledTotalPixels =
Math.ceil(comparisonWidth / sampleRate) *
Math.ceil(comparisonHeight / sampleRate);
const similarity =
((sampledTotalPixels - differentPixels) / sampledTotalPixels) * 100;
// Create page highlights (limit for performance)
const limitedRegions = differenceRegions.slice(0, 200); // Limit to 200 highlights
createPageHighlights(limitedRegions, comparisonWidth, comparisonHeight);
resolve({
similarity,
differences: differentPixels,
totalPixels: sampledTotalPixels,
differenceRegions: limitedRegions,
});
} catch (error) {
console.error("Comparison error:", error);
const errorMessage =
error?.message || error?.toString() || "Unknown comparison error";
resolve({
success: false,
error: errorMessage,
});
}
}
});
}
function createPageHighlights(
differenceRegions,
originalWidth,
originalHeight
) {
// Clear existing highlights
clearPageHighlights();
if (differenceRegions.length === 0) return;
// Get full page dimensions
const fullPageWidth = Math.max(
document.body.scrollWidth,
document.body.offsetWidth,
document.documentElement.clientWidth,
document.documentElement.scrollWidth,
document.documentElement.offsetWidth
);
const fullPageHeight = Math.max(
document.body.scrollHeight,
document.body.offsetHeight,
document.documentElement.clientHeight,
document.documentElement.scrollHeight,
document.documentElement.offsetHeight
);
// Scale factors to map from comparison coordinates to actual page coordinates
const scaleX = fullPageWidth / originalWidth;
const scaleY = fullPageHeight / originalHeight;
// Group nearby difference pixels into regions to reduce highlight count
const groupedRegions = groupDifferenceRegions(differenceRegions, 10); // 10px grouping threshold
groupedRegions.forEach((region) => {
const highlight = document.createElement("div");
highlight.className = "pp-page-highlight";
// Scale the region to actual page coordinates
const left = region.x * scaleX;
const top = region.y * scaleY;
const width = Math.max(region.width * scaleX, 4);
const height = Math.max(region.height * scaleY, 4);
// Use absolute positioning relative to the page, not viewport
// Set z-index lower than overlay so highlights appear on page behind the overlay
highlight.style.cssText = `
position: absolute !important;
left: ${left}px !important;
top: ${top}px !important;
width: ${width}px !important;
height: ${height}px !important;
background: rgba(255, 68, 68, 0.5) !important;
border: 3px solid #ff0000 !important;
pointer-events: none !important;
z-index: 999990 !important;
border-radius: 4px !important;
box-shadow: 0 0 12px rgba(255, 68, 68, 0.8) !important;
animation: pp-highlight-pulse 2s ease-in-out infinite !important;
`;
// Try different parent elements to ensure visibility
// First try to append to a container that's not affected by the overlay
const targetParent =
document.querySelector("main") ||
document.querySelector('[role="main"]') ||
document.querySelector(".main") ||
document.body;
targetParent.appendChild(highlight);
});
// Add a simple test highlight to verify highlighting works
setTimeout(() => {
const testHighlight = document.createElement("div");
testHighlight.className = "pp-page-highlight pp-test-highlight";
testHighlight.style.cssText = `
position: fixed !important;
left: 100px !important;
top: 100px !important;
width: 50px !important;
height: 50px !important;
background: rgba(0, 255, 0, 0.7) !important;
border: 3px solid #00ff00 !important;
pointer-events: none !important;
z-index: 999995 !important;
border-radius: 50% !important;
`;
document.body.appendChild(testHighlight);
// Remove test highlight after 3 seconds
setTimeout(() => {
testHighlight.remove();
}, 3000);
}, 500);
}
function groupDifferenceRegions(regions, threshold) {
if (regions.length === 0) return [];
const grouped = [];
const used = new Set();
for (let i = 0; i < regions.length; i++) {
if (used.has(i)) continue;
const group = [regions[i]];
used.add(i);
// Find nearby regions to group together
for (let j = i + 1; j < regions.length; j++) {
if (used.has(j)) continue;
const distance = Math.sqrt(
Math.pow(regions[i].x - regions[j].x, 2) +
Math.pow(regions[i].y - regions[j].y, 2)
);
if (distance <= threshold) {
group.push(regions[j]);
used.add(j);
}
}
// Create bounding box for the group
let minX = Math.min(...group.map((r) => r.x));
let minY = Math.min(...group.map((r) => r.y));
let maxX = Math.max(...group.map((r) => r.x + r.width));
let maxY = Math.max(...group.map((r) => r.y + r.height));
grouped.push({
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY,
});
}
return grouped;
}
function clearPageHighlights() {
const highlights = document.querySelectorAll(".pp-page-highlight");
highlights.forEach((highlight) => highlight.remove());
}
function showComparisonResults(result) {
const similarityElement = document.getElementById("pp-similarity-value");
const diffCountElement = document.getElementById("pp-diff-count");
if (similarityElement) {
similarityElement.textContent = `${Math.round(result.similarity)}%`;
}
if (diffCountElement) {
diffCountElement.textContent = `${result.differences} pixels`;
}
}
function clearComparison() {
if (comparisonOverlay) {
comparisonOverlay.remove();
comparisonOverlay = null;
}
clearPageHighlights();
isComparing = false;
}