-
Notifications
You must be signed in to change notification settings - Fork 57
/
snippets.js
2393 lines (2093 loc) · 67 KB
/
snippets.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
/*
* This file is part of Adblock Plus <https://adblockplus.org/>,
* Copyright (C) 2006-present eyeo GmbH
*
* Adblock Plus 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 Plus 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 Plus. If not, see <http://www.gnu.org/licenses/>.
*/
/** @module */
/* global environment */
/* eslint-env webextensions */
/* eslint no-console: "off" */
"use strict";
let [uniqueIdentifier] = URL.createObjectURL(new Blob()).match(/[^/]+$/);
// secured env and secured global variables
let ABP = getABPNamespace();
let {Object, utils} = ABP;
let {getComputedStyle, setInterval, setTimeout, performance} = ABP.window;
/**
* @typedef {object} FetchContentInfo
* @property {function} remove
* @property {Promise} result
* @property {number} timer
* @private
*/
/**
* @type {Map.<string, FetchContentInfo>}
* @private
*/
let fetchContentMap = new Map();
/**
* @type {Map.<function, Array.<function>>}
* @private
*/
let dependencyGraph = new Map();
/**
* Extract utilities from globals and return a deep-frozen object with those.
* @return {object} An object namespace with all the global utilities used by
* our snippets.
* @private
*/
function getABPNamespace()
{
/* eslint-disable no-shadow */
let {Object} = window;
let {assign, defineProperty, freeze, getOwnPropertyDescriptor,
values} = Object;
let {getComputedStyle, setInterval, setTimeout, performance} = window;
/* eslint-enable no-shadow */
// the bind is needed in Firefox or it breaks
return freeze({
Object: freeze({
assign: assign.bind(Object),
defineProperty: defineProperty.bind(Object),
getOwnPropertyDescriptor: getOwnPropertyDescriptor.bind(Object),
values: (values || function(object)
{
return this.keys(object).map(key => object[key]);
}).bind(Object)
}),
utils: freeze({
isOwnProperty: Function.call.bind(Object.prototype.hasOwnProperty)
}),
window: freeze({
getComputedStyle: getComputedStyle.bind(window),
setInterval: setInterval.bind(window),
setTimeout: setTimeout.bind(window),
performance
})
});
}
/**
* Register one or more dependencies for a specific function.
* @param {function} func The function that requires dependencies.
* @param {...function} dependencies The function function dependencies.
* @private
*/
function registerDependencies(func, ...dependencies)
{
if (dependencyGraph.has(func))
throw new Error(`duplicated ${func.name} dependencies`);
dependencyGraph.set(func, dependencies);
}
/**
* Returns a list of requirements for a function being injected as a script.
* @param {function} func A function with dependencies.
* @param {Set} [dependencies] An object that collects the unique set of
* dependencies.
* @returns {Array.<function>} All dependencies needed for the function.
* @private
*/
function resolveDependencies(func, dependencies = new Set())
{
let root = dependencies.size === 0;
if (root)
dependencies.add(func);
for (let dependency of dependencyGraph.get(func) || [])
{
if (!dependencies.has(dependency))
{
dependencies.add(dependency);
resolveDependencies(dependency, dependencies);
}
}
if (root)
return [...dependencies].slice(1);
}
/**
* Returns a potentially already resolved fetch auto cleaning, if not requested
* again, after a certain amount of milliseconds.
*
* The resolved fetch is by default `arrayBuffer` but it can be any other kind
* through the configuration object.
*
* @param {string} url The url to fetch
* @param {object} [options] Optional configuration options.
* By default is {as: "arrayBuffer", cleanup: 60000}
* @param {string} [options.as] The fetch type: "arrayBuffer", "json", "text"..
* @param {number} [options.cleanup] The cache auto-cleanup delay in ms: 60000
*
* @returns {Promise} The fetched result as Uint8Array|string.
*
* @example
* fetchContent('https://any.url.com').then(arrayBuffer => { ... })
* @example
* fetchContent('https://a.com', {as: 'json'}).then(json => { ... })
* @example
* fetchContent('https://a.com', {as: 'text'}).then(text => { ... })
* @private
*/
function fetchContent(url, {as = "arrayBuffer", cleanup = 60000} = {})
{
// make sure the fetch type is unique as the url fetching text or arrayBuffer
// will fetch same url twice but it will resolve it as expected instead of
// keeping the fetch potentially hanging forever.
let uid = as + ":" + url;
let details = fetchContentMap.get(uid) || {
remove: () => fetchContentMap.delete(uid),
result: null,
timer: 0
};
clearTimeout(details.timer);
details.timer = setTimeout(details.remove, cleanup);
if (!details.result)
{
details.result = fetch(url).then(response => response[as]());
details.result.catch(details.remove);
fetchContentMap.set(uid, details);
}
return details.result;
}
/**
* Escapes regular expression special characters in a string.
*
* The returned string may be passed to the `RegExp` constructor to match the
* original string.
*
* @param {string} string The string in which to escape special characters.
*
* @returns {string} A new string with the special characters escaped.
* @private
*/
function regexEscape(string)
{
return string.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
}
/**
* Converts a given pattern to a regular expression.
*
* @param {string} pattern The pattern to convert. If the pattern begins and
* ends with a slash (`/`), the text in between is treated as a regular
* expression; otherwise the pattern is treated as raw text.
*
* @returns {RegExp} A `RegExp` object based on the given pattern.
* @private
*/
function toRegExp(pattern)
{
if (pattern.length >= 2 && pattern[0] == "/" &&
pattern[pattern.length - 1] == "/")
return new RegExp(pattern.substring(1, pattern.length - 1));
return new RegExp(regexEscape(pattern));
}
registerDependencies(toRegExp, regexEscape);
/**
* Converts a number to its hexadecimal representation.
*
* @param {number} number The number to convert.
* @param {number} [length] The <em>minimum</em> length of the hexadecimal
* representation. For example, given the number `1024` and the length `8`,
* the function returns the value `"00000400"`.
*
* @returns {string} The hexadecimal representation of the given number.
* @private
*/
function toHex(number, length = 2)
{
let hex = number.toString(16);
if (hex.length < length)
hex = "0".repeat(length - hex.length) + hex;
return hex;
}
/**
* Converts a `Uint8Array` object into its hexadecimal representation.
*
* @param {Uint8Array} uint8Array The `Uint8Array` object to convert.
*
* @returns {string} The hexadecimal representation of the given `Uint8Array`
* object.
* @private
*/
function uint8ArrayToHex(uint8Array)
{
return uint8Array.reduce((hex, byte) => hex + toHex(byte), "");
}
/**
* Returns the value of the `cssText` property of the object returned by
* `getComputedStyle` for the given element.
*
* If the value of the `cssText` property is blank, this function computes the
* value out of the properties available in the object.
*
* @param {Element} element The element for which to get the computed CSS text.
*
* @returns {string} The computed CSS text.
* @private
*/
function getComputedCSSText(element)
{
let style = getComputedStyle(element);
let {cssText} = style;
if (cssText)
return cssText;
for (let property of style)
cssText += `${property}: ${style[property]}; `;
return cssText.trim();
}
/**
* Injects JavaScript code into the document using a temporary
* `script` element.
*
* @param {string} code The code to inject.
* @param {Array.<function|string>} [dependencies] A list of dependencies
* to inject along with the code. A dependency may be either a function or a
* string containing some executable code.
* @private
*/
function injectCode(code, dependencies = [])
{
let executable = `
(function()
{
"use strict";
let environment = ${JSON.stringify(environment)};
let ABP = window["${uniqueIdentifier}"];
if (!ABP)
{
ABP = (${getABPNamespace})();
ABP.Object.defineProperty(window, "${uniqueIdentifier}", {value: ABP});
}
let {Object, utils} = ABP;
let {getComputedStyle, setInterval, setTimeout,
performance} = ABP.window;
let debug = ${debug};
let inactiveProfile = ${inactiveProfile};
let noopProfile = ${noopProfile};
${dependencies.join("\n")}
${code}
})();
`;
let script = document.createElement("script");
script.type = "application/javascript";
script.async = false;
// Firefox 58 only bypasses site CSPs when assigning to 'src',
// while Chrome 67 and Microsoft Edge (tested on 44.17763.1.0)
// only bypass site CSPs when using 'textContent'.
if (browser.runtime.getURL("").startsWith("moz-extension://"))
{
let url = URL.createObjectURL(new Blob([executable]));
script.src = url;
document.documentElement.appendChild(script);
URL.revokeObjectURL(url);
}
else
{
script.textContent = executable;
document.documentElement.appendChild(script);
}
document.documentElement.removeChild(script);
}
/**
* Converts a function and an optional list of arguments into a string of code
* containing a function call.
*
* The function is converted to its string representation using the
* `Function.prototype.toString` method. Each argument is stringified using
* `JSON.stringify`.
*
* @param {function} func The function to convert.
* @param {...*} [params] The arguments to convert.
*
* @returns {string} The generated code containing the function call.
* @private
*/
function stringifyFunctionCall(func, ...params)
{
// Call JSON.stringify on the arguments to avoid any arbitrary code
// execution.
return `(${func})(${params.map(JSON.stringify).join(",")});`;
}
/**
* Wraps a function and its dependencies into an injector.
*
* The injector, when called with zero or more arguments, generates code that
* calls the function, with the given arguments, if any, and injects the code,
* along with any dependencies, into the document using a temporary `script`
* element.
*
* @param {function} injectable The function to wrap into an injector.
* @param {...(function|string)} [dependencies] Any dependencies of the
* function. A dependency may be either a function or a string containing
* some executable code.
*
* @returns {function} The generated injector.
* @private
*/
function makeInjector(injectable)
{
return (...args) => injectCode(stringifyFunctionCall(injectable, ...args),
resolveDependencies(injectable));
}
/**
* Hides an HTML element by setting its `style` attribute to
* `display: none !important`.
*
* @param {HTMLElement} element The HTML element to hide.
* @private
*/
function hideElement(element)
{
let {style} = element;
let hide = () =>
{
for (let [key, value] of environment.debugCSSProperties ||
[["display", "none"]])
{
if (style.getPropertyValue(key) != value ||
style.getPropertyPriority(key) != "important")
style.setProperty(key, value, "important");
}
};
hide();
// Listen for changes to the style property and if our values are unset
// then reset them.
new MutationObserver(hide).observe(element, {
attributes: true,
attributeFilter: ["style"]
});
}
/**
* Observes changes to a DOM node using a `MutationObserver`.
*
* @param {Node} target The DOM node to observe for changes.
* @param {MutationObserverInit?} [options] Options that describe what DOM
* mutations should be reported to the callback.
* @param {function} callback A function that will be called on each DOM
* mutation, taking a `MutationRecord` as its parameter.
* @private
*/
function observe(target, options, callback)
{
new MutationObserver(mutations =>
{
for (let mutation of mutations)
callback(mutation);
})
.observe(target, options);
}
/**
* Logs its arguments to the console.
*
* This may be used for testing and debugging.
*
* @alias module:content/snippets.log
*
* @param {...*} [args] The arguments to log.
*
* @since Adblock Plus 3.3
*/
function log(...args)
{
let {mark, end} = profile("log");
if (debug)
args.unshift("%c DEBUG", "font-weight: bold");
mark();
console.log(...args);
end();
}
registerDependencies(log, profile);
exports.log = log;
/**
* Similar to `log`, but does the logging in the context of the document rather
* than the content script.
*
* This may be used for testing and debugging, especially to verify that the
* injection of snippets into the document is working without any errors.
*
* @param {...*} [args] The arguments to log.
*
* @since Adblock Plus 3.3
*/
function trace(...args)
{
// We could simply use console.log here, but the goal is to demonstrate the
// usage of snippet dependencies.
log(...args);
}
registerDependencies(trace, log);
exports.trace = makeInjector(trace);
/**
* This is an implementation of the `uabinject-defuser` technique used by
* [uBlock Origin](https://github.com/uBlockOrigin/uAssets/blob/c091f861b63cd2254b8e9e4628f6bdcd89d43caa/filters/resources.txt#L640).
* @alias module:content/snippets.uabinject-defuser
*
* @since Adblock Plus 3.3
*/
function uabinjectDefuser()
{
window.trckd = true;
window.uabpdl = true;
window.uabInject = true;
window.uabDetect = true;
}
exports["uabinject-defuser"] = makeInjector(uabinjectDefuser);
/**
* Hides any HTML element or one of its ancestors matching a CSS selector if
* the text content of the element's shadow contains a given string.
* @alias module:content/snippets.hide-if-shadow-contains
*
* @param {string} search The string to look for in every HTML element's
* shadow. If the string begins and ends with a slash (`/`), the text in
* between is treated as a regular expression.
* @param {string} selector The CSS selector that an HTML element must match
* for it to be hidden.
*
* @since Adblock Plus 3.3
*/
function hideIfShadowContains(search, selector = "*")
{
let originalAttachShadow = Element.prototype.attachShadow;
// If there's no Element.attachShadow API present then we don't care, it must
// be Firefox or an older version of Chrome.
if (!originalAttachShadow)
return;
let re = toRegExp(search);
// Mutation observers mapped to their corresponding shadow roots and their
// hosts.
let shadows = new WeakMap();
function observeShadow(mutations, observer)
{
let {host, root} = shadows.get(observer) || {};
// Since it's a weak map, it's possible that either the element or its
// shadow has been removed.
if (!host || !root)
return;
// If the shadow contains the given text, check if the host or one of its
// ancestors matches the selector; if a matching element is found, hide
// it.
if (re.test(root.textContent))
{
let closest = host.closest(selector);
if (closest)
hideElement(closest);
}
}
Object.defineProperty(Element.prototype, "attachShadow", {
value(...args)
{
// Create the shadow root first. It doesn't matter if it's a closed
// shadow root, we keep the reference in a weak map.
let root = originalAttachShadow.apply(this, args);
// Listen for relevant DOM mutations in the shadow.
let observer = new MutationObserver(observeShadow);
observer.observe(root, {
childList: true,
characterData: true,
subtree: true
});
// Keep references to the shadow root and its host in a weak map. If
// either the shadow is detached or the host itself is removed from the
// DOM, the mutation observer too will be freed eventually and the entry
// will be removed.
shadows.set(observer, {host: this, root});
return root;
}
});
}
registerDependencies(hideIfShadowContains,
toRegExp,
hideElement);
exports["hide-if-shadow-contains"] = makeInjector(hideIfShadowContains);
/**
* Hides any HTML element or one of its ancestors matching a CSS selector if
* it matches the provided condition.
*
* @param {function} match The function that provides the matching condition.
* @param {string} selector The CSS selector that an HTML element must match
* for it to be hidden.
* @param {?string} [searchSelector] The CSS selector that an HTML element
* containing the given string must match. Defaults to the value of the
* `selector` argument.
* @private
*/
function hideIfMatches(match, selector, searchSelector)
{
if (searchSelector == null)
searchSelector = selector;
let callback = () =>
{
for (let element of document.querySelectorAll(searchSelector))
{
let closest = element.closest(selector);
if (closest && match(element, closest))
hideElement(closest);
}
};
new MutationObserver(callback)
.observe(document, {childList: true, characterData: true, subtree: true});
callback();
}
/**
* Hides any HTML element or one of its ancestors matching a CSS selector if
* the text content of the element contains a given string.
* @alias module:content/snippets.hide-if-contains
*
* @param {string} search The string to look for in HTML elements. If the
* string begins and ends with a slash (`/`), the text in between is treated
* as a regular expression.
* @param {string} selector The CSS selector that an HTML element must match
* for it to be hidden.
* @param {?string} [searchSelector] The CSS selector that an HTML element
* containing the given string must match. Defaults to the value of the
* `selector` argument.
*
* @since Adblock Plus 3.3
*/
function hideIfContains(search, selector = "*", searchSelector = null)
{
let re = toRegExp(search);
hideIfMatches(element => re.test(element.textContent),
selector, searchSelector);
}
exports["hide-if-contains"] = hideIfContains;
/**
* Check if an element is visible
*
* @param {Element} element The element to check visibility of.
* @param {CSSStyleDeclaration} style The computed style of element.
* @param {?Element} closest The closest parent to reach.
* @return {bool} Whether the element is visible.
* @private
*/
function isVisible(element, style, closest)
{
if (style.getPropertyValue("display") == "none")
return false;
let visibility = style.getPropertyValue("visibility");
if (visibility == "hidden" || visibility == "collapse")
return false;
if (!closest || element == closest)
return true;
let parent = element.parentElement;
if (!parent)
return true;
return isVisible(parent, getComputedStyle(parent), closest);
}
/**
* Hides any HTML element matching a CSS selector if the visible text content
* of the element contains a given string.
* @alias module:content/snippets.hide-if-contains-visible-text
*
* @param {string} search The string to match to the visible text. Is considered
* visible text that isn't hidden by CSS properties or other means.
* If the string begins and ends with a slash (`/`), the text in between is
* treated as a regular expression.
* @param {string} selector The CSS selector that an HTML element must match
* for it to be hidden.
* @param {?string} [searchSelector] The CSS selector that an HTML element
* containing the given string must match. Defaults to the value of the
* `selector` argument.
*
* @since Adblock Plus 3.6
*/
function hideIfContainsVisibleText(search, selector, searchSelector = null)
{
/**
* Determines if the text inside the element is visible.
*
* @param {Element} element The element we are checking.
* @param {?CSSStyleDeclaration} style The computed style of element. If
* falsey it will be queried.
* @returns {bool} Whether the text is visible.
* @private
*/
function isTextVisible(element, style)
{
if (!style)
style = getComputedStyle(element);
if (style.getPropertyValue("opacity") == "0")
return false;
if (style.getPropertyValue("font-size") == "0px")
return false;
let color = style.getPropertyValue("color");
// if color is transparent...
if (color == "rgba(0, 0, 0, 0)")
return false;
if (style.getPropertyValue("background-color") == color)
return false;
return true;
}
/**
* Check if a pseudo element has visible text via `content`.
*
* @param {Element} element The element to check visibility of.
* @param {string} pseudo The `::before` or `::after` pseudo selector.
* @return {string} The pseudo content or an empty string.
* @private
*/
function getPseudoContent(element, pseudo)
{
let style = getComputedStyle(element, pseudo);
if (!isVisible(element, style) || !isTextVisible(element, style))
return "";
let {content} = style;
if (content && content !== "none")
{
let strings = [];
// remove all strings, in quotes, including escaping chars, putting
// instead `\x01${string-index}` in place, which is not valid CSS,
// so that it's safe to parse it back at the end of the operation.
content = content.trim().replace(
/(["'])(?:(?=(\\?))\2.)*?\1/g,
value => `\x01${strings.push(value.slice(1, -1)) - 1}`
);
// replace attr(...) with the attribute value or an empty string,
// ignoring units and fallback values, as these do not work, or have,
// any meaning in the CSS `content` property value.
content = content.replace(
/\s*attr\(\s*([^\s,)]+)[^)]*?\)\s*/g,
(_, name) => element.getAttribute(name) || ""
);
// replace back all `\x01${string-index}` values with their corresponding
// strings, so that the outcome is a real, cleaned up, `content` value.
return content.replace(/\x01(\d+)/g, (_, index) => strings[index]);
}
return "";
}
/**
* Returns the visible text content from an element and its descendants.
*
* @param {Element} element The element whose visible text we want.
* @param {Element} closest The closest parent to reach while checking
* for visibility.
* @param {?CSSStyleDeclaration} style The computed style of element. If
* falsey it will be queried.
* @returns {string} The text that is visible.
* @private
*/
function getVisibleContent(element, closest, style)
{
let checkClosest = !style;
if (checkClosest)
style = getComputedStyle(element);
if (!isVisible(element, style, checkClosest && closest))
return "";
let text = getPseudoContent(element, ":before");
for (let node of element.childNodes)
{
switch (node.nodeType)
{
case Node.ELEMENT_NODE:
text += getVisibleContent(node,
element,
getComputedStyle(node));
break;
case Node.TEXT_NODE:
if (isTextVisible(element, style))
text += node.nodeValue;
break;
}
}
return text + getPseudoContent(element, ":after");
}
let re = toRegExp(search);
let seen = new WeakSet();
hideIfMatches(
(element, closest) =>
{
if (seen.has(element))
return false;
seen.add(element);
let text = getVisibleContent(element, closest);
let result = re.test(text);
if (debug && text.length)
log(result, re, text);
return result;
},
selector,
searchSelector
);
}
exports["hide-if-contains-visible-text"] = hideIfContainsVisibleText;
/**
* Hides any HTML element or one of its ancestors matching a CSS selector if
* the text content of the element contains a given string and, optionally, if
* the element's computed style contains a given string.
* @alias module:content/snippets.hide-if-contains-and-matches-style
*
* @param {string} search The string to look for in HTML elements. If the
* string begins and ends with a slash (`/`), the text in between is treated
* as a regular expression.
* @param {string} selector The CSS selector that an HTML element must match
* for it to be hidden.
* @param {string?} [searchSelector] The CSS selector that an HTML element
* containing the given string must match. Defaults to the value of the
* `selector` argument.
* @param {string?} [style] The string that the computed style of an HTML
* element matching `selector` must contain. If the string begins and ends
* with a slash (`/`), the text in between is treated as a regular
* expression.
* @param {string?} [searchStyle] The string that the computed style of an HTML
* element matching `searchSelector` must contain. If the string begins and
* ends with a slash (`/`), the text in between is treated as a regular
* expression.
*
* @since Adblock Plus 3.3.2
*/
function hideIfContainsAndMatchesStyle(search, selector = "*",
searchSelector = null, style = null,
searchStyle = null)
{
if (searchSelector == null)
searchSelector = selector;
let searchRegExp = toRegExp(search);
let styleRegExp = style ? toRegExp(style) : null;
let searchStyleRegExp = searchStyle ? toRegExp(searchStyle) : null;
new MutationObserver(() =>
{
for (let element of document.querySelectorAll(searchSelector))
{
if (searchRegExp.test(element.textContent) &&
(!searchStyleRegExp ||
searchStyleRegExp.test(getComputedCSSText(element))))
{
let closest = element.closest(selector);
if (closest && (!styleRegExp ||
styleRegExp.test(getComputedCSSText(closest))))
hideElement(closest);
}
}
})
.observe(document, {childList: true, characterData: true, subtree: true});
}
exports["hide-if-contains-and-matches-style"] = hideIfContainsAndMatchesStyle;
/**
* Hides any HTML element or one of its ancestors matching a CSS selector if a
* descendant of the element matches a given CSS selector and, optionally, if
* the element's computed style contains a given string.
* @alias module:content/snippets.hide-if-has-and-matches-style
*
* @param {string} search The CSS selector against which to match the
* descendants of HTML elements.
* @param {string} selector The CSS selector that an HTML element must match
* for it to be hidden.
* @param {?string} [searchSelector] The CSS selector that an HTML element
* containing the specified descendants must match. Defaults to the value of
* the `selector` argument.
* @param {?string} [style] The string that the computed style of an HTML
* element matching `selector` must contain. If the string begins and ends
* with a slash (`/`), the text in between is treated as a regular
* expression.
* @param {?string} [searchStyle] The string that the computed style of an HTML
* element matching `searchSelector` must contain. If the string begins and
* ends with a slash (`/`), the text in between is treated as a regular
* expression.
*
* @since Adblock Plus 3.4.2
*/
function hideIfHasAndMatchesStyle(search, selector = "*",
searchSelector = null, style = null,
searchStyle = null)
{
if (searchSelector == null)
searchSelector = selector;
let styleRegExp = style ? toRegExp(style) : null;
let searchStyleRegExp = searchStyle ? toRegExp(searchStyle) : null;
new MutationObserver(() =>
{
for (let element of document.querySelectorAll(searchSelector))
{
if (element.querySelector(search) &&
(!searchStyleRegExp ||
searchStyleRegExp.test(getComputedCSSText(element))))
{
let closest = element.closest(selector);
if (closest && (!styleRegExp ||
styleRegExp.test(getComputedCSSText(closest))))
hideElement(closest);
}
}
})
.observe(document, {childList: true, subtree: true});
}
exports["hide-if-has-and-matches-style"] = hideIfHasAndMatchesStyle;
/**
* Hides any HTML element or one of its ancestors matching a CSS selector if
* the background image of the element matches a given pattern.
* @alias module:content/snippets.hide-if-contains-image
*
* @param {string} search The pattern to look for in the background images of
* HTML elements. This must be the hexadecimal representation of the image
* data for which to look. If the string begins and ends with a slash (`/`),
* the text in between is treated as a regular expression.
* @param {string} selector The CSS selector that an HTML element must match
* for it to be hidden.
* @param {?string} [searchSelector] The CSS selector that an HTML element
* containing the given pattern must match. Defaults to the value of the
* `selector` argument.
*
* @since Adblock Plus 3.4.2
*/
function hideIfContainsImage(search, selector, searchSelector)
{
if (searchSelector == null)
searchSelector = selector;
let searchRegExp = toRegExp(search);
new MutationObserver(() =>
{
for (let element of document.querySelectorAll(searchSelector))
{
let style = getComputedStyle(element);
let match = style["background-image"].match(/^url\("(.*)"\)$/);
if (match)
{
fetchContent(match[1]).then(content =>
{
if (searchRegExp.test(uint8ArrayToHex(new Uint8Array(content))))
{
let closest = element.closest(selector);
if (closest)
hideElement(closest);
}
});
}
}
})
.observe(document, {childList: true, subtree: true});
}
exports["hide-if-contains-image"] = hideIfContainsImage;
/**
* Readds to the document any removed HTML elements that match a CSS selector.
*
* @param {string} selector The CSS selector that a removed HTML element should
* match for it to be added back.
* @param {string?} [parentSelector] The CSS selector that a removed HTML
* element's former parent should match for it to be added back.
*
* @since Adblock Plus 3.3
*/
function readd(selector, parentSelector = null)
{
observe(document, {childList: true, subtree: true}, mutation =>
{
if (mutation.removedNodes &&
(!parentSelector || (mutation.target instanceof Element &&
mutation.target.matches(parentSelector))))
{
for (let node of mutation.removedNodes)
{
if (node instanceof HTMLElement && node.matches(selector))
{
// We don't have the location of the element in its former parent,
// but it's usually OK to just add it at the end.
mutation.target.appendChild(node);
}
}
}
});
}