-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadblock-picreplacement.js
807 lines (743 loc) · 27.3 KB
/
adblock-picreplacement.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
/*
* This file is part of AdBlock <https://getadblock.com/>,
* Copyright (C) 2013-present Adblock, Inc.
*
* AdBlock is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* AdBlock is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with AdBlock. If not, see <http://www.gnu.org/licenses/>.
*/
/* For ESLint: List any global identifiers used in this file below */
/* global browser, translate, onReady */
const { hostname } = window.location;
let totalSwaps = 0;
const hideElements = [];
const hiddenElements = [];
const cssRules = [];
const minDimension = 60;
const typeMap = new Map([
['img', 'IMAGE'],
['input', 'IMAGE'],
['picture', 'IMAGE'],
['audio', 'MEDIA'],
['video', 'MEDIA'],
['frame', 'SUBDOCUMENT'],
['iframe', 'SUBDOCUMENT'],
['object', 'OBJECT'],
['embed', 'OBJECT'],
]);
const imageSizesMap = new Map([
['NONE', 0],
['wide', 1],
['tall', 2],
['skinnywide', 4],
['skinnytall', 8],
['big', 16],
['small', 32],
]);
const deferred = new Map();
let urls;
function getURLFromElement(element) {
if (element.localName !== 'object') {
return element.currentSrc || element.src;
}
if (element.data) {
return element.data;
}
for (const child of element.children) {
if (child.localName === 'param' && child.name === 'movie' && child.value) {
return new URL(child.value, document.baseURI).href;
}
}
return null;
}
// a slightly faster alternative to just using 'querySelectorAll'
// Note: this function may return:
// - an HTMLCOllection of elements,
// - or a NodeList of elements
// - or an Array with 1 element
const queryDOM = function (selectorText) {
if (selectorText.startsWith('#')) {
const element = document.getElementById(selectorText.substr(1));
if (element) {
return [element];
}
return [];
}
if (selectorText.startsWith('.')) {
const classes = selectorText.substr(1).replace(/\./g, ' ');
return document.getElementsByClassName(classes);
}
// Default to `querySelectorAll`
return document.querySelectorAll(selectorText);
};
const imageSwap = {
/**
* @param {Object} data Information about the element
* @param {Node} data.el
* @param {Boolean} [data.blocked]
* @param {Object} [data.size]
* @param {Number} [data.dimension]
* @param {CSSStyleDeclaration} [data.computedStyle]
* @param {Function} callback Called when replacement was done
* */
replaceSection(data, callback) {
const { el } = data;
// We may have already replaced this section...
if (el.getAttribute('picreplacementreplaced')) {
return;
}
el.setAttribute('picreplacementreplaced', true);
if (data.blocked) {
const size = this.getStyle(data, 'backgroundPosition').match(/^(\w+) (\w+)$/);
if (size) {
// Restore el.width & el.height to whatever they were before AdBlock.
const dims = { width: size[1], height: size[2] };
for (const dim in dims) {
if (dims[dim] === '-1px') {
el.removeAttribute(dim);
} else {
el.setAttribute(dim, dims[dim]);
}
}
}
}
const oldCssText = el.style.cssText;
el.style.setProperty('visibility', 'hidden', 'important');
el.style.setProperty('display', 'block', 'important');
this.replace(data, callback);
el.style.cssText = oldCssText; // Re-hide the section
},
// Given details about a picture and a target rectangle, return details
// about how to place the picture in the target.
//
// pic object contains
// x - width
// y - height
// left - max crop allowed from left
// right - max crop allowed from right
// top - max crop allowed from top
// bot - max crop allowed from bottom
//
// target object contains
// x - width
// y - height
//
// result object contains
// x - width of background image to use (before crop)
// y - height of background image to use (before crop)
// top - amount to offset top of photo in target to cause a vertical crop
// left - amount to offset left of photo in target to cause a horizontal crop
// width - width of visible area of result image
// height - height of visible area of result image
// offsettop - amount to pad with blank space above picture
// offsetleft - amount to pad with blank space to left of picture
// These are used to center a picture in a tall or wide target
fit(pic, target) {
const p = pic;
const t = target;
// Step 0: if t.ratio > p.ratio, rotate |p| and |t| about their NW<->SE axes.
if (!p.x) {
p.x = p.width;
}
if (!p.y) {
p.y = p.height;
}
if (!t.x) {
t.x = t.width;
}
if (!t.y) {
t.y = t.height;
}
if (!p.left) {
p.left = 0;
}
if (!p.right) {
p.right = 0;
}
if (!t.left) {
t.left = 0;
}
if (!t.right) {
t.right = 0;
}
// Our math in Step 1 and beyond relies on |t| being skinner than |p|. We
// rotate |t| and |p| about their NW<->SE axis if needed to make that true.
const tRatio = t.x / t.y;
const pRatio = p.x / p.y;
if (tRatio > pRatio) {
const { rotate } = this;
rotate(pic);
rotate(target);
const result = this.fit(pic, target);
rotate(pic);
rotate(target);
rotate(result);
return result;
}
// |t| is skinnier than |p|, so we need to crop the picture horizontally.
// Step 1: Calculate |cropX|: total horizontal crop needed.
const cropMax = Math.max(p.left + p.right, 0.001);
// Crop as much as we must, but not past the max allowed crop.
const cropX = Math.min(p.x - p.y * tRatio, cropMax);
// Step 2: Calculate how much of that crop should be done on the left side
// of the picture versus the right.
// We will execute the crop by giving a background-image a CSS left offset,
// so we only have to calculate the left crop and the right crop will happen
// naturally due to the size of the target area not fitting the entire image.
const cropLeft = p.left * (cropX / cropMax);
// Step 3: Calculate how much we must scale up or down the original picture.
const scale = t.x / (p.x - cropX);
// Scale the original picture and crop amounts in order to determine the width
// and height of the visible display area, the x and y dimensions of the image
// to display in it, and the crop amount to offset the image. The end result
// is an image positioned to show the correct pixels in the target area.
const result = {};
result.x = Math.round(p.x * scale);
result.y = Math.round(p.y * scale);
result.left = Math.round(cropLeft * scale);
result.width = Math.round(t.x);
result.height = Math.round(result.y);
// Step 4: Add vertical padding if we weren't allowed to crop as much as we
// liked, resulting in an image not tall enough to fill the target.
result.offsettop = Math.round((t.y - result.height) / 2);
// Done!
result.top = 0;
result.offsetleft = 0;
return result;
},
// Rotate a picture/target about its NW<->SE axis.
rotate(objectToRotate) {
const o = objectToRotate;
const pairs = [['x', 'y'], ['top', 'left'], ['bot', 'right'],
['offsettop', 'offsetleft'], ['width', 'height']];
pairs.forEach((pair) => {
const [a, b] = pair;
let tmp;
if (o[a] || o[b]) {
tmp = o[b]; o[b] = o[a]; o[a] = tmp; // swap
}
});
},
dim(data, prop) {
function intFor(val) {
// Match two or more digits; treat < 10 as missing. This lets us set
// dims that look good for e.g. 1px tall ad holders (cnn.com footer.)
const match = (val || '').match(/^([1-9][0-9]+)(px)?$/);
if (!match) {
return undefined;
}
return parseInt(match[1], 10);
}
return intFor(imageSwap.getStyle(data, prop));
},
parentDim(data, prop) {
let { el } = data;
if (hostname === 'www.facebook.com') {
return undefined;
}
let result;
while (!result && el.parentNode) {
const parentData = { el: el.parentNode };
result = this.dim(parentData, prop);
el = el.parentNode;
}
return result;
},
getSize(data) {
const { el } = data;
let t = {
x: this.dim(data, 'width'),
y: this.dim(data, 'height'),
position: this.getStyle(data, 'position'),
};
if (!t.x && !t.y && !typeMap.get(el.localName) && el.hasChildNodes()) {
// Since we're now injecting a 'user' stylesheet to hide elements, temporarily
// setting the display to block to unhide the element will not work, so..
// attempt to determine the size of one of children
for (let i = 0; i < el.children.length; i++) {
const nextChildData = { el: el.children[i] };
t = imageSwap.getSize(nextChildData);
if (t.x && t.y) {
break;
}
}
}
// Make it rectangular if ratio is appropriate, or if we only know one dim
// and it's so big that the 180k pixel max will force the pic to be skinny.
if (t.x && !t.y && t.x > 400) {
t.type = imageSizesMap.get('wide');
} else if (t.y && !t.x && t.y > 400) {
t.type = imageSizesMap.get('tall');
} else if ( // false unless (t.x && t.y)
(Math.max(t.x, t.y) / Math.min(t.x, t.y) >= 1.5)
&& (Math.max(t.x, t.y) / Math.min(t.x, t.y) < 7)
) {
t.type = (t.x > t.y ? imageSizesMap.get('wide') : imageSizesMap.get('tall'));
} else if (Math.max(t.x, t.y) / Math.min(t.x, t.y) > 7) { // false unless (t.x && t.y)
t.type = (t.x > t.y ? imageSizesMap.get('skinnywide') : imageSizesMap.get('skinnytall'));
}
if (!t.type) { // we didn't choose wide/tall
t.type = ((t.x || t.y) > 125 ? imageSizesMap.get('big') : imageSizesMap.get('small'));
}
return t;
},
// Returns placement details to replace |el|, or null
// if we do not have enough info to replace |el|.
placementFor(data, callback) {
let t;
const { el } = data;
const that = this;
// if there's previously calculate size, use it
if (data.size != null && Object.keys(data.size).length) {
t = data.size;
} else {
t = this.getSize(data);
if (this.isInvalidSize(t)) {
callback(false);
return false;
}
}
// Let's not go ahead if the parent element of |el| has display none
const parent = el.parentNode;
if (!(parent.offsetWidth || parent.offsetHeight || parent.getClientRects().length)) {
callback(false);
return false;
}
browser.runtime.sendMessage({
command: 'channels.getrandomlisting',
opts: {
width: t.x, height: t.y, type: t.type, position: t.position,
},
}).then((picture) => {
const pic = picture;
if (!pic || pic.disabledOnPage) {
callback(false);
return false;
}
if (typeof pic.height === 'string') {
pic.height = Number(pic.height);
}
if (typeof pic.width === 'string') {
pic.width = Number(pic.width);
}
// If we only have one dimension, we may choose to use the picture's ratio;
// but don't go over 180k pixels (so e.g. 1000x__ doesn't insert a 1000x1000
// picture (cnn.com)). And if an ancestor has a size, don't exceed that.
const max = 180000;
if (t.x && !t.y) {
const newY = Math.round(Math.min(pic.height * t.x / pic.width, max / t.x));
const parentY = that.parentDim(data, 'height');
t.y = (parentY ? Math.min(newY, parentY) : newY);
}
if (t.y && !t.x) {
const newX = Math.round(Math.min(pic.width * t.y / pic.height, max / t.y));
const parentX = that.parentDim(data, 'width');
t.x = (parentX ? Math.min(newX, parentX) : newX);
}
const result = that.fit(pic, t);
result.url = pic.url;
result.attributionUrl = pic.attributionUrl;
result.photoTitle = pic.title;
result.infoUrl = pic.attributionUrl;
result.type = t.type;
result.t = t;
result.listingHeight = pic.listingHeight;
result.listingWidth = pic.listingWidth;
result.channelName = pic.channelName;
result.customImage = pic.customImage;
callback(result);
return true;
});
return undefined;
},
// Create a container with the new image and overlay
// Return an object with the container and its children nodes
createNewPicContainer(placement) {
// Container, inherit some CSS from replaced element
const imageSwapContainer = document.createElement('div');
imageSwapContainer.id = `ab-image-swap-container-${new Date().getTime()}`;
// Wrapper, necessary to set postition: relative
const imageSwapWrapper = document.createElement('div');
imageSwapWrapper.classList.add('ab-image-swap-wrapper');
// New image
let newPic;
if (placement.customImage === true) {
newPic = document.createElement('div');
browser.storage.local.get(placement.url).then((savedCustomImageData) => {
const base = newPic.attachShadow({ mode: 'closed' });
// a closed shadow root is utilized to protect users images
// from being accessed by websites where the images are injected
const innerHTMLText = `:host {
content: url("${savedCustomImageData[placement.url].src}");
}`;
const styleTag = document.createElement('style');
styleTag.type = 'text/css';
styleTag.textContent = innerHTMLText;
base.appendChild(styleTag);
});
} else {
newPic = document.createElement('img');
newPic.src = placement.url;
newPic.alt = translate('image_of_channel', translate(placement.channelName));
newPic.setAttribute('referrerpolicy', 'no-referrer');
}
newPic.classList.add('picreplacement-image');
// Overlay info card
const infoCardOverlay = document.createElement('div');
infoCardOverlay.classList.add('picinjection-infocard');
const overlayLogo = document.createElement('img');
overlayLogo.classList.add('ab-logo-header');
overlayLogo.src = browser.runtime.getURL('icons/dark_theme/logo.svg');
overlayLogo.alt = translate('adblock_logo');
const overlayIcons = document.createElement('div');
overlayIcons.classList.add('ab-icons-header');
const seeIcon = document.createElement('i');
seeIcon.innerText = 'remove_red_eye';
seeIcon.classList.add('ab-material-icons');
const settingsIcon = document.createElement('i');
settingsIcon.innerText = 'settings';
settingsIcon.classList.add('ab-material-icons');
const closeIcon = document.createElement('i');
closeIcon.innerText = 'close';
closeIcon.classList.add('ab-material-icons');
overlayIcons.appendChild(seeIcon);
overlayIcons.appendChild(settingsIcon);
overlayIcons.appendChild(closeIcon);
infoCardOverlay.appendChild(overlayLogo);
infoCardOverlay.appendChild(overlayIcons);
imageSwapWrapper.appendChild(newPic);
imageSwapWrapper.appendChild(infoCardOverlay);
imageSwapContainer.appendChild(imageSwapWrapper);
return {
container: imageSwapContainer,
imageWrapper: imageSwapWrapper,
image: newPic,
overlay: infoCardOverlay,
logo: overlayLogo,
icons: overlayIcons,
closeIcon,
settingsIcon,
seeIcon,
};
},
// Add a <style> tag into the host page's header to style all the HTML we use to replace the ad
// including the container, the image, the overlay, the logo and the icons
injectCSS(data, placement, containerID) {
const adblockLogoWidth = placement.type === imageSizesMap.get('skinnywide') ? '81px' : '114px';
const adblockLogoHeight = placement.type === imageSizesMap.get('skinnywide') ? '20px' : '29px';
const materialIconsURL = browser.runtime.getURL('/icons/MaterialIcons-Regular.woff2');
const styleTag = document.createElement('style');
styleTag.type = 'text/css';
styleTag.textContent = `
div#${containerID} {
position: ${this.getStyle(data, 'position')};
width: fit-content;
height: fit-content;
font-family: 'Lato', Arial, sans-serif;
line-height: normal;
box-sizing: initial;
top: ${this.getStyle(data, 'top')};
left: ${this.getStyle(data, 'left')};
right: ${this.getStyle(data, 'right')};
bottom: ${this.getStyle(data, 'bottom')};
/* nytimes.com float:right ad at top is on the left without this */
float: ${this.getStyle(data, 'float')};
}
div#${containerID} > .ab-image-swap-wrapper {
position: relative;
display: inline-grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
grid-template-areas: 'overlap';
}
div#${containerID} > .ab-image-swap-wrapper > .picreplacement-image {
width: ${placement.width}px;
height: ${placement.height}px;
background-position: -${placement.left}px -${placement.top}px;
background-size: ${placement.x}px ${placement.y}px;
margin: ${placement.offsettop}px ${placement.offsetleft}px;
border: none; /* some sites borders all imgs */
grid-area: overlap;
}
div#${containerID} > .ab-image-swap-wrapper > .picinjection-infocard {
display: none;
padding: 3px;
position: absolute;
min-width: ${placement.width}px;
min-height: ${placement.height}px;
box-sizing: border-box;
border: 2px solid rgb(128, 128, 128);
color: black;
background-color: rgba(0, 0, 0, 0.7);
margin: ${placement.offsettop}px ${placement.offsetleft}px;
grid-area: overlap;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
div#${containerID} > .ab-image-swap-wrapper > .picinjection-infocard:hover,
div#${containerID} > .ab-image-swap-wrapper > .picreplacement-image:hover ~ .picinjection-infocard {
display: block;
}
div#${containerID} > .ab-image-swap-wrapper > .picinjection-infocard > .ab-logo-header {
float: left;
border: none; /* some sites borders all imgs */
margin-top: 0;
margin-left: 0;
height: ${adblockLogoHeight};
width: ${adblockLogoWidth};
}
div#${containerID} > .ab-image-swap-wrapper > .picinjection-infocard > .ab-icons-header {
margin-top: 0px;
margin-right: 0px;
vertical-align: middle;
line-height: ${adblockLogoHeight};
height: ${adblockLogoHeight};
float: right;
display: inline;
}
div#${containerID} > .ab-image-swap-wrapper > .picinjection-infocard .ab-material-icons {
color: #666666;
margin-right: 8px;
}
div#${containerID} > .ab-image-swap-wrapper > .picinjection-infocard .ab-material-icons:hover {
color: white;
}
div#${containerID} > .ab-image-swap-wrapper > .picinjection-infocard .ab-material-icons:last-child {
margin-right: 0;
}
div#${containerID} > .ab-image-swap-wrapper .ab-material-icons {
font-family: 'Material Icons';
color: #999;
cursor: pointer;
font-weight: normal;
font-style: normal;
font-size: 24px;
display: inline-block;
line-height: 1;
text-transform: none;
letter-spacing: normal;
word-wrap: normal;
white-space: nowrap;
direction: ltr;
vertical-align: middle;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: normal;
src: local('Material Icons'), url(${materialIconsURL});
}
`;
document.head.appendChild(styleTag);
},
setupEventHandlers(placement, containerNodes) {
containerNodes.image.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
return false;
}, false);
containerNodes.image.addEventListener('error', () => {
containerNodes.container.parentNode.removeChild(containerNodes.container);
return false;
}, false);
containerNodes.image.addEventListener('abort', () => {
containerNodes.container.parentNode.removeChild(containerNodes.container);
return false;
}, false);
containerNodes.seeIcon.addEventListener('click', () => {
const url = encodeURIComponent(placement.attributionUrl);
const width = placement.listingWidth;
const height = placement.listingHeight;
const channel = placement.channelName;
const queryStrings = `url=${url}&width=${width}&height=${height}&channel=${channel}`;
browser.runtime.sendMessage({ command: 'openTab', urlToOpen: browser.runtime.getURL(`adblock-picreplacement-imageview.html?${queryStrings}`) });
});
containerNodes.settingsIcon.addEventListener('click', () => {
browser.runtime.sendMessage({ command: 'openTab', urlToOpen: browser.runtime.getURL('options.html#mab-image-swap') });
});
containerNodes.closeIcon.addEventListener('click', () => {
containerNodes.container.parentNode.removeChild(containerNodes.container);
});
},
// Given a target element, replace it with a picture.
// Returns the replacement element if replacement works, or null if the target
// element could not be replaced.
replace(elementData, callback) {
const that = this;
const data = elementData;
that.placementFor(data, (placement) => {
if (!placement) {
callback(false);
return false; // don't know how to replace |data.el|
}
// We only want to replace 2 ads per page
if (totalSwaps > 1) {
callback(false);
return false;
}
const containerNodes = that.createNewPicContainer(placement);
that.injectCSS(data, placement, containerNodes.container.id);
that.setupEventHandlers(placement, containerNodes);
data.el.parentNode.insertBefore(containerNodes.container, data.el);
// Force showing the image in case it was not showing
containerNodes.image.style.display = 'inline-block';
callback(true);
return true;
});
},
translate(key) {
return browser.i18n.getMessage(key);
},
isInvalidSize(size) {
return !size.x || !size.y || size.x < minDimension || size.y < minDimension;
},
// Check if an element is nested in any element in array
// Return true if |el| is nested or a duplicate
isNested(el, elements) {
let isNestedElement = false;
for (let j = 0; j < elements.length; j++) {
const otherElement = elements[j].el;
if (el !== otherElement && otherElement.contains(el)) {
isNestedElement = true;
break;
}
}
return isNestedElement;
},
// Return property value of the given |data.el|
getStyle(elementData, property) {
const data = elementData;
const alreadyComputed = data.computedStyle;
if (alreadyComputed) {
return alreadyComputed[property];
}
const inlineValue = data.el.style[property];
if (inlineValue) {
return inlineValue;
}
const attribute = data.el.getAttribute(property);
if (attribute) {
return attribute;
}
data.computedStyle = window.getComputedStyle(data.el);
return data.computedStyle[property];
},
// Function called after an ad was replaced with an image
done(replaced) {
if (replaced) {
// on some sites, such as freepik.com with absolute positioning,
// the position of other elements is calculated before our pic replacement is injected.
// a forced window resize event repaints the page to correctly lay it out
totalSwaps += 1;
window.dispatchEvent(new Event('resize'));
browser.runtime.sendMessage({ command: 'channels.recordOneAdReplaced' });
}
},
}; // end imageSwap
// hideElement may get call after the page has completed loading on certain sites that have infinite
// scroll for example. If the user is on on these infinite scroll sites, such as FB, then attempt
// to do a pic replacement
const checkElement = function (element) {
const data = {
el: element,
blocked: !!typeMap.get(element.localName),
};
if (
document.readyState === 'complete'
|| (window.top === window && hostname === 'www.facebook.com')
) {
imageSwap.replaceSection(data, imageSwap.done);
} else {
hideElements.push(data);
}
};
// when the page has completed loading:
// 1) check the settings object to verify that image swap is enabled
// 2) get the currently loaded CSS hiding rules (if available)
// 3) find any hidden elements using the hiding rules from #1 that meet the
// minimum dimensions required. if so, add them to an array
// 4) find any hidden elements that were captured from the hideElement() function that meet the
// minimum dimensions required. if so, add them to an array
// 5) sort the array by size -- we want to replace the large elements first
// 6) process the sorted array, attempting to do a pic replacment for each element
onReady(async () => {
const settings = await browser.runtime.sendMessage({ command: 'getSettings' });
if (!settings || !settings.picreplacement) {
return;
}
let elementsData = [];
for (let i = 0; i < cssRules.length; i++) {
const elements = queryDOM(cssRules[i]);
for (let j = 0; j < elements.length; j++) {
const data = { el: elements[j] };
hiddenElements.push(data);
}
}
for (const [selector] of deferred) {
for (const element of document.querySelectorAll(selector)) {
if (urls.has(getURLFromElement(element))) {
checkElement(element);
}
}
}
// If no elements to swap, stop
if (!hiddenElements.length && !hideElements.length) {
return;
}
const allElements = hideElements.concat(hiddenElements);
for (let i = 0; i < allElements.length; i++) {
const data = allElements[i];
const size = imageSwap.getSize(data);
if (!imageSwap.isInvalidSize(size)) {
data.size = size;
data.dimension = (size.x * size.y);
// Add element only if it is not nested in other
// elements and it's not equal to other elements
if (!imageSwap.isNested(data.el, allElements)) {
elementsData.push(data);
}
}
}
// Put first elements of larger dimensions
elementsData = elementsData.sort((a, b) => (b.dimension > a.dimension ? 1 : -1));
for (let i = 0; i < elementsData.length; i++) {
imageSwap.replaceSection(elementsData[i], imageSwap.done);
}
});
browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.command === 'addSelector') {
if (document.readyState === 'complete') {
const elements = queryDOM(request.hidingSelector);
for (let j = 0; j < elements.length; j++) {
const data = { el: elements[j] };
const size = imageSwap.getSize(data);
if (!imageSwap.isInvalidSize(size)) {
data.size = size;
data.dimension = (size.x * size.y);
imageSwap.replaceSection(data, imageSwap.done);
}
}
} else {
cssRules.push(request.hidingSelector);
}
sendResponse({});
}
if (request.command === 'addBlockingSelector') {
urls = deferred.get(request.selector) || new Set();
deferred.set(request.selector, urls);
urls.add(request.url);
sendResponse({});
}
});