-
Notifications
You must be signed in to change notification settings - Fork 1
/
content.js
1191 lines (1010 loc) · 41.7 KB
/
content.js
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// calculate the sum of every dark pattern
let countdown_value = 0;
let popup_value = 0;
let malicious_link_count = 0;
let display_count_down_count = 0;
let prechecked_value = 0;
let stock_value = 0;
let image_value = 0;
let countdownElements = [];
let stockElements = [];
let precheckedElements = [];
let hiddenElements = [];
let ImageApiElements = [];
let allImagesElements = new Map();
let currentCountdownIndex = -1;
let currentStockIndex = -1;
let currentPrecheckedIndex = -1;
let currentHiddenIndex = -1;
let currentImageIndex = -1;
let typeElement;
let patternType = 'countdown';
let leftElement;
let rightElement;
let numElement;
let images = new Map();
const pureNumber = /^\d+$/;
// regex for countdown
const countdown = /(?:\d{1,2}\s*:\s*){1,3}\d{1,2}|(?:\d{1,2}\s*(?:days?|hours?|minutes?|seconds?|[a-zA-Z]{1,3}\.?)\s*){2,4}/gi;
// regex for not countdown
const notCountdown = /(?:\d{1,2}\s*:\s*){4,}\d{1,2}|(?:\d{1,2}\s*(?:days?|hours?|minutes?|seconds?|[a-zA-Z]{1,3}\.?)\s*){5,}/gi;
// stock keywords for only...left
const stockKey = /(?:only\s*\d+\s*left)|(?:almost\s*sold\s*out)/i;
// Get the current URL
const currentPageURL = window.location.href;
const countdownValues = {};
countdownValues[currentPageURL] = 0;
// List of keywords to check for
const keywords = ['expire', 'expires', 'offer', 'offers', 'promotion', 'promotions', 'discount', 'discounts', 'forgot', 'receive', 'voucher', 'reward', 'rewards'];
// Add a flag to track if a centered popup has been found
let centeredPopupFound = false;
var imageUrl = chrome.runtime.getURL('images/floating_background.png');
window.onload = async function() {
setInterval(async function() {
// clone the body of the page
oldBody = document.body.cloneNode(true);
setTimeout(async function() {
await traverseDOM(oldBody, document.body);
}, 1000);
setTimeout(async function() {
await loopDOM(document.body);
}, 1000);
}, 3000);
// setInterval(async function() {
// await loopDOM(document.body);
// }, 10000);
// Get all form inputs (checkboxes and radio buttons)
const formInputs = document.querySelectorAll('input');
// Iterate through form inputs
formInputs.forEach(input => {
// Check if the input is visible
const isHidden = input.hidden;
const isDisplayNone = window.getComputedStyle(input).getPropertyValue('display') === 'none';
const rect = input.getBoundingClientRect();
const isVisible = (
rect.top > 0 &&
rect.left > 0 &&
rect.bottom < (window.innerHeight || document.documentElement.clientHeight) &&
rect.right < (window.innerWidth || document.documentElement.clientWidth)
);
if (input.checked && !isHidden && !isDisplayNone && isVisible) {
// Highlight the preselected input label
const label = document.querySelector(`label[for="${input.id}"]`);
if (label) {
console.log(input, rect);
prechecked_value++;
// addCornerBorder(label);
label.style.border = '3px solid black';
if (!precheckedElements.includes(label)) {
precheckedElements.push(label);
sortElements(precheckedElements);
addHoverDiv(label, 'prechecked');
}
}
}
});
const isSearchEnginePage = window.location.href.includes('google.com/search');
// Configuration for the observer (observe changes to attributes)
const config = { attributes: true, attributeOldValue: true, childList: true, subtree: true, attributeFilter: ['style', 'class'] };
if (!isSearchEnginePage) {
setTimeout(function() {
handleOverlaying(document.body);
}, 0);
}
// Create a new MutationObserver instance
const observer = new MutationObserver(async function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList') {
// Check each added node in the mutation
mutation.addedNodes.forEach(function(node) {
handleOverlaying(node);
});
// Handle removed nodes
mutation.removedNodes.forEach(function(node) {
handleRemovedNodes(node);
});
} else if (mutation.type === 'attributes' && (mutation.attributeName === 'style' || mutation.attributeName === 'class')) {
const target = mutation.target;
const previousStyle = mutation.oldValue;
const currentStyle = target.getAttribute('style');
const previousClass = mutation.oldValue;
const currentClass = target.getAttribute('class');
const previousDisplay = getDisplayValue(previousStyle, previousClass);
const currentDisplay = getDisplayValue(currentStyle, currentClass);
if (previousDisplay !== currentDisplay) {
// console.log('display: ', target);
handleOverlaying(target);
}
}
});
// observer.disconnect();
// Check countdown after every mutation
// countdown_value = 0;
// Set sleep time to avoid too frequent mutations
// await new Promise(resolve => { setTimeout(resolve, 1500) });
// Change to async function for stability
if (display_count_down_count != countdown_value) {
display_count_down_count = countdown_value;
}
if (centeredPopupFound) {
popup_value = 1;
} else {
popup_value = 0;
}
chrome.runtime.sendMessage({
countdown_value: countdown_value,
malicious_link_count: malicious_link_count,
prechecked_value: prechecked_value,
popup_value: popup_value,
stock_value: stock_value,
image_value: image_value,
}, function(response) {
// console.log("checked ", countdown_value, malicious_link_count, prechecked_value, popup_value, stock_value, image_value);
});
// reconnect the observer
observer.observe(document.body, config);
});
// Start observing the DOM with the given configuration
// observer.observe(document.body, config);
// Check hidden every 5 secs
setInterval(async () => {
// disconnect the observer to avoid duplicate checking
observer.disconnect();
findHidden(document.body);
// console.log(`Found ${hiddenElements.length} malicious nodes`);
// reconnect the observer
observer.observe(document.body, config);
}, 3000);
}
let overlayingDivs = [];
async function findDeepestOverlayingDiv(node, depth) {
let deepestOverlayingDiv = null;
let textContent = node.textContent.toLowerCase();
let foundKeyword = keywords.find(keyword => textContent.includes(keyword));
let includesImg;
const maxDepth = 5;
if (depth >= maxDepth) {
return null;
}
// iterate all child nodes
for (let i = 0; i < node.childNodes.length; i++) {
const childNode = node.childNodes[i];
if (childNode instanceof HTMLElement &&
childNode.childNodes.length > 0 &&
(foundKeyword || includesImg)
) {
if (isElementOverlaying(childNode) || isElementFixedAndVisible(childNode)) {
// if current node is overlaying,set it as deepest overlaying div
deepestOverlayingDiv = childNode;
// console.log('deep: ', deepestOverlayingDiv, deepestOverlayingDiv.getBoundingClientRect());
}
const childDeepestOverlayingDiv = await findDeepestOverlayingDiv(childNode, depth + 1);
if (childDeepestOverlayingDiv !== null) {
// if there is deeper overlaying div,update the deepest overlaying div
deepestOverlayingDiv = childDeepestOverlayingDiv;
}
}
// Add a delay here to yield to the main thread
if (i % 10 === 0) {
await new Promise(resolve => setTimeout(resolve, 0));
}
}
return deepestOverlayingDiv;
}
// Check if the element is overlaying
function isElementOverlaying(element) {
const rect = element.getBoundingClientRect();
const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
// Define a threshold for overlap
const overlapThreshold = 0.9;
// Calculate the area of intersection with the viewport
const intersectionArea = Math.max(0, Math.min(rect.right, viewportWidth) - Math.max(rect.left, 0)) *
Math.max(0, Math.min(rect.bottom, viewportHeight) - Math.max(rect.top, 0));
// Calculate the area of the viewport
const viewportArea = viewportWidth * viewportHeight;
// Determine if the element covers a significant portion of the viewport
return rect.width >= viewportWidth * 0.95 && rect.height >= viewportHeight * 0.95 && intersectionArea / viewportArea >= overlapThreshold;
}
function isElementFixedAndVisible(element) {
const computedStyle = window.getComputedStyle(element);
const isFixed = computedStyle.position === 'fixed';
const isVisible = element.offsetParent !== null;
return isFixed && isVisible;
}
function getDisplayValue(styleString, classString) {
const styleMatch = styleString && styleString.match(/(?:^|\s)display:\s*([^;]*)(?:;|$)/i);
const classMatch = classString && classString.match(/(?:^|\s)display:\s*([^;]*)(?:;|$)/i);
return styleMatch ? styleMatch[1] : classMatch ? classMatch[1] : null;
}
async function handleOverlaying(element) {
const deepestOverlayingDiv = await findDeepestOverlayingDiv(element, 0);
if (deepestOverlayingDiv !== null) {
console.log("deepest overlaying: ", deepestOverlayingDiv);
centeredPopupFound = false;
findCenteredPopup(deepestOverlayingDiv, 0);
}
}
function findCenteredPopup(element, depth) {
const maxDepth = 1;
if (centeredPopupFound || depth > maxDepth) return;
let textContent = element.textContent.toLowerCase();
let foundKeyword = keywords.find(keyword => textContent.includes(keyword));
// Get the position and size information of the element
const boundingBox = element.getBoundingClientRect();
// Get the width and height of the viewport
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
// Define a margin value
const margin = 20;
// Check if the element is centered with the margin
if (
Math.abs(boundingBox.left + boundingBox.width / 2 - viewportWidth / 2) < margin &&
Math.abs(boundingBox.top + boundingBox.height / 2 - viewportHeight / 2) < margin &&
boundingBox.height < viewportHeight * 0.8 &&
boundingBox.width < viewportWidth * 0.7 &&
foundKeyword
) {
console.log('centered popup:', element);
// addCornerBorder(element);
// element.style.border = "5px solid black"
addOverlay(element);
centeredPopupFound = true;
return;
}
// Recursively iterate through child div elements
const childDivs = element.querySelectorAll('div');
for (const childDiv of childDivs) {
findCenteredPopup(childDiv, depth + 1);
}
}
function sortElements(elements) {
elements.sort((a, b) => {
const rectA = a.getBoundingClientRect();
const rectB = b.getBoundingClientRect();
if (rectA.top !== rectB.top) {
return rectA.top - rectB.top;
} else {
return rectA.left - rectB.left;
}
});
}
// add cornerborder to the corresponding element
function addCornerBorder(element) {
const cornerSize = '3px solid black';
const cornerOffset = '0px';
const cornerStyle = `
position: absolute;
width: 10px;
height: 10px;
z-index: 9999999;
!important;
`;
const fragment = document.createDocumentFragment();
const topLeftCorner = document.createElement('div');
topLeftCorner.classList.add('corner-element');
topLeftCorner.style = `
${cornerStyle}
top: ${cornerOffset};
left: ${cornerOffset};
border-left: ${cornerSize};
border-top: ${cornerSize};
`;
const topRightCorner = document.createElement('div');
topRightCorner.classList.add('corner-element');
topRightCorner.style = `
${cornerStyle}
top: ${cornerOffset};
right: ${cornerOffset};
border-right: ${cornerSize};
border-top: ${cornerSize};
`;
const bottomLeftCorner = document.createElement('div');
bottomLeftCorner.classList.add('corner-element');
bottomLeftCorner.style = `
${cornerStyle}
bottom: ${cornerOffset};
left: ${cornerOffset};
border-left: ${cornerSize};
border-bottom: ${cornerSize};
`;
const bottomRightCorner = document.createElement('div');
bottomRightCorner.classList.add('corner-element');
bottomRightCorner.style = `
${cornerStyle}
bottom: ${cornerOffset};
right: ${cornerOffset};
border-right: ${cornerSize};
border-bottom: ${cornerSize};
`;
fragment.appendChild(topLeftCorner);
fragment.appendChild(topRightCorner);
fragment.appendChild(bottomLeftCorner);
fragment.appendChild(bottomRightCorner);
element.appendChild(fragment);
}
function removeCornerBorder(element) {
const cornerElements = element.querySelectorAll('.corner-element');
cornerElements.forEach(cornerElement => {
cornerElement.remove();
});
}
// pop up button
function toggleFloatingButton() {
const button = document.createElement('div');
const leftBtn = document.createElement('button');
const rightBtn = document.createElement('button');
const close = document.createElement('button');
const num = document.createElement('p');
const type = document.createElement('p');
leftBtn.classList.add('left-btn');
leftElement = leftBtn;
rightBtn.classList.add('right-btn');
rightElement = rightBtn;
num.classList.add('total-count');
numElement = num;
type.classList.add('type');
typeElement = type;
close.classList.add('close-floating');
button.classList.add('floating-button');
// type.innerText = patternType;
button.style.position = 'fixed';
button.style.bottom = '20px';
button.style.right = '20px';
button.style.zIndex = '99999';
button.style.cursor = 'move';
let isDragging = false;
let startPosX, startPosY;
let startMouseX, startMouseY;
button.addEventListener('mousedown', (e) => {
isDragging = true;
startPosX = parseFloat(button.style.right);
startPosY = parseFloat(button.style.bottom);
startMouseX = e.clientX;
startMouseY = e.clientY;
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const offsetX = e.clientX - startMouseX;
const offsetY = e.clientY - startMouseY;
const newRight = startPosX - offsetX;
const newBottom = startPosY - offsetY;
// Get the size of the viewport
const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
// calculate boundary
const maxRight = viewportWidth - button.offsetWidth;
const maxBottom = viewportHeight - button.offsetHeight;
// limit button inside
const limitedRight = Math.min(maxRight, Math.max(0, newRight));
const limitedBottom = Math.min(maxBottom, Math.max(0, newBottom));
button.style.right = `${limitedRight}px`;
button.style.bottom = `${limitedBottom}px`;
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
document.body.appendChild(button);
button.appendChild(close);
button.appendChild(num);
button.appendChild(leftBtn);
button.appendChild(rightBtn);
button.appendChild(type);
close.addEventListener('click', function() {
button.remove();
removeBackground();
removeCornerBorder(document.body);
});
setDefaultCount(currentCountdownIndex, countdownElements);
}
function setDefaultCount(currentIndex, elements) {
if (elements.length > 0) {
leftElement.innerText = (currentIndex > 0) ? currentIndex : elements.length;
} else {
leftElement.innerText = '';
}
numElement.innerText = (currentIndex >= 0) ? currentIndex + 1 : '';
if (elements.length > 0) {
rightElement.innerText = (currentIndex < elements.length - 1) ? currentIndex + 2 : 1;
} else {
rightElement.innerText = '';
}
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.command === "toggleFloatingButton") {
const existingButton = document.querySelector('.floating-button');
if (!existingButton) {
toggleFloatingButton();
}
}
if (message.type) {
patternType = message.type
typeElement.innerText = patternType;
// console.log(patternType);
showPattern();
}
if (message.default) {
patternType = message.default
typeElement.innerText = patternType;
console.log(message.default);
showPattern();
}
rightElement.removeEventListener('click', handleRightButtonClickWrapper);
leftElement.removeEventListener('click', handleLeftButtonClickWrapper);
rightElement.addEventListener('click', handleRightButtonClickWrapper);
leftElement.addEventListener('click', handleLeftButtonClickWrapper);
});
function showPattern() {
const existingBackground = document.querySelector('.rgbbackground');
if (patternType == 'preselected') {
setDefaultCount(currentPrecheckedIndex, precheckedElements);
if (precheckedElements.length > 0) {
currentPrecheckedIndex = 0;
scrollToCurrentCountdownElement(currentPrecheckedIndex, precheckedElements);
} else {
existingBackground.remove();
removeCornerBorder(document.body);
}
} else if (patternType == 'countdown') {
setDefaultCount(currentCountdownIndex, countdownElements);
if (countdownElements.length > 0) {
currentCountdownIndex = 0;
scrollToCurrentCountdownElement(currentCountdownIndex, countdownElements);
} else {
existingBackground.remove();
removeCornerBorder(document.body);
}
} else if (patternType == 'hidden info') {
setDefaultCount(currentHiddenIndex, hiddenElements);
if (hiddenElements.length > 0) {
currentHiddenIndex= 0;
scrollToCurrentCountdownElement(currentHiddenIndex, hiddenElements);
} else {
existingBackground.remove();
removeCornerBorder(document.body);
}
} else if (patternType == 'stock') {
setDefaultCount(currentStockIndex, stockElements);
if (stockElements.length > 0) {
currentStockIndex = 0;
scrollToCurrentCountdownElement(currentStockIndex, stockElements);
} else {
existingBackground.remove();
removeCornerBorder(document.body);
}
} else if (patternType == 'image') {
setDefaultCount(currentImageIndex, ImageApiElements);
if (ImageApiElements.length > 0) {
currentImageIndex = 0;
scrollToCurrentCountdownElement(currentImageIndex, ImageApiElements);
} else {
existingBackground.remove();
removeCornerBorder(document.body);
}
} else {
setDefaultCount(-1, []);
existingBackground.remove();
removeCornerBorder(document.body);
}
}
function handleRightButtonClick(currentIndex, elements) {
if (currentIndex < elements.length - 1) {
currentIndex++;
} else {
currentIndex = 0;
}
console.log('index: ', currentIndex);
return currentIndex;
}
function handleRightButtonClickWrapper() {
if (patternType == 'countdown' && countdownElements.length > 0) {
currentCountdownIndex = handleRightButtonClick(currentCountdownIndex, countdownElements);
scrollToCurrentCountdownElement(currentCountdownIndex, countdownElements);
} else if (patternType == 'preselected' && precheckedElements.length > 0) {
currentPrecheckedIndex = handleRightButtonClick(currentPrecheckedIndex, precheckedElements);
scrollToCurrentCountdownElement(currentPrecheckedIndex, precheckedElements);
} else if (patternType == 'hidden info' && hiddenElements.length > 0) {
currentHiddenIndex = handleRightButtonClick(currentHiddenIndex, hiddenElements);
scrollToCurrentCountdownElement(currentHiddenIndex, hiddenElements);
} else if (patternType == 'stock' && stockElements.length > 0) {
currentStockIndex = handleRightButtonClick(currentStockIndex, stockElements);
scrollToCurrentCountdownElement(currentStockIndex, stockElements);
} else if (patternType == 'image' && ImageApiElements.length > 0) {
currentImageIndex = handleRightButtonClick(currentImageIndex, ImageApiElements);
scrollToCurrentCountdownElement(currentImageIndex, ImageApiElements);
}
}
function handleLeftButtonClick(currentIndex, elements) {
if (currentIndex > 0) {
currentIndex--;
} else {
currentIndex = elements.length - 1;
}
return currentIndex;
}
function handleLeftButtonClickWrapper() {
if (patternType == 'countdown' && countdownElements.length > 0) {
currentCountdownIndex = handleLeftButtonClick(currentCountdownIndex, countdownElements);
scrollToCurrentCountdownElement(currentCountdownIndex, countdownElements);
} else if (patternType == 'preselected' && precheckedElements.length > 0) {
currentPrecheckedIndex = handleLeftButtonClick(currentPrecheckedIndex, precheckedElements);
scrollToCurrentCountdownElement(currentPrecheckedIndex, precheckedElements);
} else if (patternType == 'hidden info' && hiddenElements.length > 0) {
currentHiddenIndex = handleLeftButtonClick(currentHiddenIndex, hiddenElements);
scrollToCurrentCountdownElement(currentHiddenIndex, hiddenElements);
} else if (patternType == 'stock' && stockElements.length > 0) {
currentStockIndex = handleLeftButtonClick(currentStockIndex, stockElements);
scrollToCurrentCountdownElement(currentStockIndex, stockElements);
} else if (patternType == 'image' && ImageApiElements.length > 0) {
currentImageIndex = handleLeftButtonClick(currentImageIndex, ImageApiElements);
scrollToCurrentCountdownElement(currentImageIndex, ImageApiElements);
}
}
function scrollToCurrentCountdownElement(currentIndex, elements) {
const currentElement = elements[currentIndex];
if (currentElement) {
currentElement.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center"
});
removeCornerBorder(document.body);
addBackground();
setTimeout(() => {
const backgroundDiv = document.querySelector('.rgbbackground');
addCornerBorder(currentElement);
updateClip(backgroundDiv, currentElement);
}, 1000);
setDefaultCount(currentIndex, elements);
console.log('index: ', currentIndex, 'list: ', elements, 'element: ', currentElement, 'length:', elements.length);
}
}
function addBackground() {
const existingBackground = document.querySelector('.rgbbackground');
if (existingBackground) {
existingBackground.remove();
}
const overlayDiv = document.createElement('div');
overlayDiv.classList.add('rgbbackground');
// set style
overlayDiv.style.position = 'fixed';
overlayDiv.style.top = '0';
overlayDiv.style.left = '0';
overlayDiv.style.right = '0';
overlayDiv.style.bottom = '0';
overlayDiv.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
overlayDiv.style.zIndex = '9998';
document.body.appendChild(overlayDiv);
overlayDiv.addEventListener('click', function() {
overlayDiv.remove();
removeCornerBorder(document.body);
});
}
function updateClip(overlayDiv, selectedElement) {
const selectedElementRect = selectedElement.getBoundingClientRect();
overlayDiv.style.clipPath = `polygon(
0% 0%,
100% 0%,
100% ${selectedElementRect.top}px,
${selectedElementRect.left}px ${selectedElementRect.top}px,
${selectedElementRect.left}px ${selectedElementRect.bottom}px,
${selectedElementRect.right}px ${selectedElementRect.bottom}px,
${selectedElementRect.right}px ${selectedElementRect.top}px,
100% ${selectedElementRect.top}px,
100% 100%,
0% 100%
)`;
}
function removeBackground() {
const existingBackground = document.querySelector('.rgbbackground');
if (existingBackground) {
existingBackground.remove();
}
}
async function loopDOM(node) {
// check if the node is an image
const imgElements = node.querySelectorAll('img.base-img__inner.lazyload.base-img__cover');
let num = 0;
imgElements.forEach(img => {
img.dataset.num = num;
num++;
let src = img.getAttribute('data-src') || img.getAttribute('src');
let testImg = new Image();
testImg.onload = async function() {
if (this.width > 800 && this.height > 600 && !allImagesElements.has(src) && !src.includes('.gif')) {
allImagesElements.set(src, img.dataset.num);
images.set(img.dataset.num, img);
console.log(`sent map size is: ${allImagesElements.size}`);
if (allImagesElements.size > 0) {
await fetch('http://localhost:8081/post/imgDetect', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
imgs: Object.fromEntries(allImagesElements)
})
})
.then(response => response.json())
.then(retArray => {
console.log(retArray);
const numArray = retArray.map(item => item.num);
for (const num of numArray) {
console.log(images.get(num));
if (!ImageApiElements.includes(images.get(num))) {
ImageApiElements.push(images.get(num));
sortElements(ImageApiElements);
}
}
})
.catch(err => console.log(err));
}
image_value = ImageApiElements.length;
}
};
testImg.onerror = function() {
console.error('Error loading image:', src);
};
testImg.src = src;
});
}
// loop through all text nodes
async function traverseDOM(oldNode, node) {
var children = node.childNodes;
var oldChildren = oldNode.childNodes;
if(node.tagName === 'STYLE' || node.tagName === 'SCRIPT') {
return; // Ignore style and script tags
}
// check if the node is an image
// const imgElements = document.querySelectorAll('img.base-img__inner.lazyload.base-img__cover');
// imgElements.forEach(img => {
// let src = img.getAttribute('data-src') || img.getAttribute('src');
// let testImg = new Image();
// testImg.onload = function() {
// if(this.width > 800 && this.height > 600 && !allImagesElements.has(src)) {
// allImagesElements.set(src, img);
// if (!ImageApiElements.includes(img)) {
// ImageApiElements.push(img);
// sortElements(ImageApiElements);
// }
// image_value = ImageApiElements.length;
// }
// };
// testImg.onerror = function() {
// console.error('Error loading image:', src);
// };
// testImg.src = src;
// });
for(var i = 0; i < children.length; i++) {
if(children[i].nodeType === 3) { // text node
// check if the text node is a stock
if(stockKey.test(children[i].nodeValue)){
const stockElement = children[i].parentNode;
stockElement.style.border = '3px solid black';
if (!stockElements.includes(stockElement)) {
stockElements.push(stockElement);
sortElements(stockElements);
addHoverDiv(stockElement, 'stock');
}
stock_value = stockElements.length;
}
// check if the text node is a countdown
if(pureNumber.test(children[i].nodeValue)){
if(!oldChildren || (oldChildren[i] && children[i].nodeValue !== oldChildren[i].nodeValue)) {
let aimNode = children[i].parentNode.parentNode;
let allTexts = extractAllTextNodes(aimNode).join(''); // get all text nodes in the same level
if (countdown.test(allTexts) && !notCountdown.test(allTexts)) {
const countdownElement = children[i].parentNode.parentNode;
countdownElement.style.border = '3px solid black';
if (!countdownElements.includes(countdownElement)) {
countdownElements.push(countdownElement);
sortElements(countdownElements);
addHoverDiv(countdownElement, 'countdown');
}
countdown_value = countdownElements.length;
}
}
}
// Add processed class to mark this element has been processed
// children[i].classList.add('processed');
}
// recursively traverse the DOM tree
if (oldChildren[i]) {
traverseDOM(oldChildren[i], children[i]);
}
}
}
// extract all text nodes in the same level of element
function extractAllTextNodes(element, result = []) {
let children = element.childNodes;
for (let i = 0; i < children.length; i++) {
let child = children[i];
if (child.nodeType === 3) { // if it is a text node
result.push(child.nodeValue);
} else if (child.nodeType === 1) { // if it is an element node
extractAllTextNodes(child, result);
}
}
return result;
}
async function findHidden(body) {
for (var i = 0; i < body.childNodes.length; i++) {
catchHidden(body.childNodes[i]);
}
}
function catchHidden(node) {
// This is your current filter processing on node
let style = window.getComputedStyle(node.parentNode, null)
let parentStyle = window.getComputedStyle(node.parentNode.parentNode, null)
let fontSize = style.getPropertyValue('font-size');
fontSize = parseFloat(fontSize);
if (fontSize <= 12
&& node.nodeType === 3
&& !isFooter(node)
&& match_hidden(node.nodeValue)
&& node.parentNode.tagName !== 'STYLE'
&& node.parentNode.tagName !== 'SCRIPT'
&& node.parentNode.nodeName !== 'A') {
// node.parentNode.style.color = "red";
node.parentNode.style.display = "block";
node.parentNode.style.visibility = "visible";
// Add black border to hidden text
// console.log(`Found hidden info, className: ${node.className}, fontSize: ${fontSize}`, node, node.parentNode);
const hoverDiv = node.parentNode.querySelector('.tooltip');
/**
if (!hoverDiv) {
addHoverEffect(node.parentNode,2);
}**/
if (!hiddenElements.includes(node.parentNode)) {
if (currentPageURL.includes('amazon')) {
if (node.parentNode.className instanceof String
&& !node.parentNode.className.includes('vjs-modal-dialog-description')) {
// temp condition for AMAZON
hiddenElements.push(node.parentNode);
sortElements(hiddenElements);
addHoverDiv(node.parentNode, 'hidden info');
}
}
else {
hiddenElements.push(node.parentNode);
sortElements(hiddenElements);
addHoverDiv(node.parentNode, 'hidden info');
}
labelPattern(node);
}
};
if (!currentPageURL.includes('amazon')
&& style.color
&& parentStyle.backgroundColor
&& node.nodeType === 3) {
let similarity = colorSimilarityNormalized(getRGBArray(parentStyle.backgroundColor),
getRGBArray(style.color));
if (similarity >= 0.9
&& similarity < 1
&& node.parentNode.style.visibility === "visible") {
// console.log(`Found similar colour, className: ${node.className},
// fontSize: ${fontSize}, similarity: ${similarity}, ${node}, ${node.parentNode}`);
// Add black border to hidden text
const hoverDiv = node.parentNode.querySelector('.tooltip');
/**if (!hoverDiv) {
addHoverEffect(node.parentNode,2);
}**/
if (!hiddenElements.includes(node.parentNode)) {
hiddenElements.push(node.parentNode);
sortElements(hiddenElements);
addHoverDiv(node.parentNode, 'hidden info');
labelPattern(node);
}
}
};
if (node.parentNode.hasAttribute('href')
&& (node.parentNode.getAttribute('href').startsWith('http')
|| node.parentNode.getAttribute('href').includes('.html'))) {
// console.log(`Found link, className: ${node.className}, fontSize: ${fontSize}`);
}
if (node.hasChildNodes()) {
for(let child of node.childNodes) {
catchHidden(child);
}
}
malicious_link_count = hiddenElements.length;
};
/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Start of helper functions
*/
// Helper function to calculate the similarity between two colArrs
function colorSimilarityNormalized(rgb1, rgb2) {
let rDiff = rgb1[0] - rgb2[0];
let gDiff = rgb1[1] - rgb2[1];
let bDiff = rgb1[2] - rgb2[2];
let maxEuclideanDist = Math.sqrt(Math.pow(255, 2) * 3);
let dist = Math.sqrt(Math.pow(rDiff,2) + Math.pow(gDiff,2) + Math.pow(bDiff,2));
// Range of similarity is [0, 1]
return 1 - (dist / maxEuclideanDist);
}
// Helper function to fetch rgb values from a color string
function getRGBArray(colorStr) {
// Remove "rgb(", "rgba(", ")" and spaces,
// then split into an array with the red, green, and blue values
let colorArr = colorStr.replace(/rgba?\(|\)|\s/g, '').split(',');
// Convert the color values to numbers
colorArr = colorArr.map(numStr => Number(numStr));
// If the colorStr was in "rgba" format, remove the alpha value
if (colorArr.length > 3) colorArr.pop();
return colorArr;
}
// Helper function to get formatted iframe from iframe text
function getIframe(textIframe) {
let parser = new DOMParser();
let dom = parser.parseFromString(textIframe, 'text/html');
return dom.querySelector('iframe');
}
// Fetch the nearest parent className
function checkClassName(element, keywords) {
if (element === null) {