Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Delta Between Two Patch Sets: lib/content/elemHideEmulation.js

Issue 29713565: Issue 6437 - Filter out patterns that do not match DOM mutations (Closed) Base URL: https://hg.adblockplus.org/adblockpluscore/
Left Patch Set: Rebase Created March 20, 2018, 9:33 a.m.
Right Patch Set: Process plain selectors on DOM mutations Created April 24, 2018, 1:56 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « no previous file | test/browser/elemHideEmulation.js » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 /* 1 /*
2 * This file is part of Adblock Plus <https://adblockplus.org/>, 2 * This file is part of Adblock Plus <https://adblockplus.org/>,
3 * Copyright (C) 2006-present eyeo GmbH 3 * Copyright (C) 2006-present eyeo GmbH
4 * 4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify 5 * Adblock Plus is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as 6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation. 7 * published by the Free Software Foundation.
8 * 8 *
9 * Adblock Plus is distributed in the hope that it will be useful, 9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. 15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
16 */ 16 */
17 17
18 "use strict"; 18 "use strict";
19 19
20 const {textToRegExp, filterToRegExp, splitSelector} = require("../common"); 20 const {textToRegExp, filterToRegExp, splitSelector} = require("../common");
21 const {indexOf} = require("../coreUtils");
21 22
22 let MIN_INVOCATION_INTERVAL = 3000; 23 let MIN_INVOCATION_INTERVAL = 3000;
23 const MAX_SYNCHRONOUS_PROCESSING_TIME = 50; 24 const MAX_SYNCHRONOUS_PROCESSING_TIME = 50;
24 const abpSelectorRegexp = /:-abp-([\w-]+)\(/i; 25 const abpSelectorRegexp = /:-abp-([\w-]+)\(/i;
25 26
26 function getCachedPropertyValue(object, name, defaultValueFunc = () => {}) 27 function getCachedPropertyValue(object, name, defaultValueFunc = () => {})
27 { 28 {
28 let value = object[name]; 29 let value = object[name];
29 if (typeof value == "undefined") 30 if (typeof value == "undefined")
30 Object.defineProperty(object, name, {value: value = defaultValueFunc()}); 31 Object.defineProperty(object, name, {value: value = defaultValueFunc()});
31 return value; 32 return value;
32 } 33 }
33 34
34 /** Return position of node from parent. 35 /** Return position of node from parent.
35 * @param {Node} node the node to find the position of. 36 * @param {Node} node the node to find the position of.
36 * @return {number} One-based index like for :nth-child(), or 0 on error. 37 * @return {number} One-based index like for :nth-child(), or 0 on error.
37 */ 38 */
38 function positionInParent(node) 39 function positionInParent(node)
39 { 40 {
40 let {children} = node.parentNode; 41 return indexOf(node.parentNode.children, node) + 1;
41 for (let i = 0; i < children.length; i++) 42 }
42 if (children[i] == node) 43
43 return i + 1; 44 function makeSelector(node, selector = "")
44 return 0;
45 }
46
47 function makeSelector(node, selector)
48 { 45 {
49 if (node == null) 46 if (node == null)
50 return null; 47 return null;
51 if (!node.parentElement) 48 if (!node.parentElement)
52 { 49 {
53 let newSelector = ":root"; 50 let newSelector = ":root";
54 if (selector) 51 if (selector)
55 newSelector += " > " + selector; 52 newSelector += " > " + selector;
56 return newSelector; 53 return newSelector;
57 } 54 }
(...skipping 162 matching lines...) Expand 10 before | Expand all | Expand 10 after
220 // Just in case the getSelectors() generator above had to run some heavy 217 // Just in case the getSelectors() generator above had to run some heavy
221 // document.querySelectorAll() call which didn't produce any results, make 218 // document.querySelectorAll() call which didn't produce any results, make
222 // sure there is at least one point where execution can pause. 219 // sure there is at least one point where execution can pause.
223 yield null; 220 yield null;
224 } 221 }
225 222
226 function PlainSelector(selector) 223 function PlainSelector(selector)
227 { 224 {
228 this._selector = selector; 225 this._selector = selector;
229 this.maybeDependsOnAttributes = /[#.]|\[.+\]/.test(selector); 226 this.maybeDependsOnAttributes = /[#.]|\[.+\]/.test(selector);
227 this.dependsOnDOM = this.maybeDependsOnAttributes;
Manish Jethani 2018/04/24 13:58:32 OK, since Trac #6618 is rejected we have to proces
230 } 228 }
231 229
232 PlainSelector.prototype = { 230 PlainSelector.prototype = {
233 /** 231 /**
234 * Generator function returning a pair of selector 232 * Generator function returning a pair of selector
235 * string and subtree. 233 * string and subtree.
236 * @param {string} prefix the prefix for the selector. 234 * @param {string} prefix the prefix for the selector.
237 * @param {Node} subtree the subtree we work on. 235 * @param {Node} subtree the subtree we work on.
238 * @param {StringifiedStyle[]} styles the stringified style objects. 236 * @param {StringifiedStyle[]} styles the stringified style objects.
239 */ 237 */
(...skipping 29 matching lines...) Expand all
269 get maybeDependsOnAttributes() 267 get maybeDependsOnAttributes()
270 { 268 {
271 return this._innerSelectors.some( 269 return this._innerSelectors.some(
272 selector => selector.maybeDependsOnAttributes 270 selector => selector.maybeDependsOnAttributes
273 ); 271 );
274 }, 272 },
275 273
276 *getSelectors(prefix, subtree, styles) 274 *getSelectors(prefix, subtree, styles)
277 { 275 {
278 for (let element of this.getElements(prefix, subtree, styles)) 276 for (let element of this.getElements(prefix, subtree, styles))
279 yield [makeSelector(element, ""), element]; 277 yield [makeSelector(element), element];
280 }, 278 },
281 279
282 /** 280 /**
283 * Generator function returning selected elements. 281 * Generator function returning selected elements.
284 * @param {string} prefix the prefix for the selector. 282 * @param {string} prefix the prefix for the selector.
285 * @param {Node} subtree the subtree we work on. 283 * @param {Node} subtree the subtree we work on.
286 * @param {StringifiedStyle[]} styles the stringified style objects. 284 * @param {StringifiedStyle[]} styles the stringified style objects.
287 */ 285 */
288 *getElements(prefix, subtree, styles) 286 *getElements(prefix, subtree, styles)
289 { 287 {
(...skipping 24 matching lines...) Expand all
314 } 312 }
315 313
316 ContainsSelector.prototype = { 314 ContainsSelector.prototype = {
317 requiresHiding: true, 315 requiresHiding: true,
318 dependsOnDOM: true, 316 dependsOnDOM: true,
319 dependsOnCharacterData: true, 317 dependsOnCharacterData: true,
320 318
321 *getSelectors(prefix, subtree, styles) 319 *getSelectors(prefix, subtree, styles)
322 { 320 {
323 for (let element of this.getElements(prefix, subtree, styles)) 321 for (let element of this.getElements(prefix, subtree, styles))
324 yield [makeSelector(element, ""), subtree]; 322 yield [makeSelector(element), subtree];
325 }, 323 },
326 324
327 *getElements(prefix, subtree, styles) 325 *getElements(prefix, subtree, styles)
328 { 326 {
329 let actualPrefix = (!prefix || incompletePrefixRegexp.test(prefix)) ? 327 let actualPrefix = (!prefix || incompletePrefixRegexp.test(prefix)) ?
330 prefix + "*" : prefix; 328 prefix + "*" : prefix;
331 329
332 let elements = scopedQuerySelectorAll(subtree, actualPrefix); 330 let elements = scopedQuerySelectorAll(subtree, actualPrefix);
331
333 if (elements) 332 if (elements)
334 { 333 {
334 let lastRoot = null;
335 for (let element of elements) 335 for (let element of elements)
336 { 336 {
337 // For a filter like div:-abp-contains(Hello) and a subtree like
338 // <div id="a"><div id="b"><div id="c">Hello</div></div></div>
339 // we're only interested in div#a
340 if (lastRoot && lastRoot.contains(element))
341 {
342 yield null;
343 continue;
344 }
345
346 lastRoot = element;
347
337 if (this._regexp && this._regexp.test(element.textContent)) 348 if (this._regexp && this._regexp.test(element.textContent))
338 yield element; 349 yield element;
339 else 350 else
340 yield null; 351 yield null;
341 } 352 }
342 } 353 }
343 } 354 }
344 }; 355 };
345 356
346 function PropsSelector(propertyExpression) 357 function PropsSelector(propertyExpression)
(...skipping 105 matching lines...) Expand 10 before | Expand all | Expand 10 after
452 return getCachedPropertyValue( 463 return getCachedPropertyValue(
453 this, "_dependsOnCharacterData", 464 this, "_dependsOnCharacterData",
454 () => this.selectors.some(selector => selector.dependsOnCharacterData) 465 () => this.selectors.some(selector => selector.dependsOnCharacterData)
455 ); 466 );
456 }, 467 },
457 468
458 matchesMutationTypes(mutationTypes) 469 matchesMutationTypes(mutationTypes)
459 { 470 {
460 let mutationTypeMatchMap = getCachedPropertyValue( 471 let mutationTypeMatchMap = getCachedPropertyValue(
461 this, "_mutationTypeMatchMap", 472 this, "_mutationTypeMatchMap",
462 () => new Map([ 473 () => new Map([
Manish Jethani 2018/03/20 09:41:33 This is a cached property also so the map gets cre
463 // All types of DOM-dependent patterns are affected by mutations of 474 // All types of DOM-dependent patterns are affected by mutations of
464 // type "childList". 475 // type "childList".
465 ["childList", true], 476 ["childList", true],
466 ["attributes", this.maybeDependsOnAttributes], 477 ["attributes", this.maybeDependsOnAttributes],
467 ["characterData", this.dependsOnCharacterData] 478 ["characterData", this.dependsOnCharacterData]
468 ]) 479 ])
469 ); 480 );
470 481
471 for (let mutationType of mutationTypes) 482 for (let mutationType of mutationTypes)
472 { 483 {
(...skipping 45 matching lines...) Expand 10 before | Expand all | Expand 10 after
518 { 529 {
519 return patterns.some(pattern => pattern.dependsOnCharacterData); 530 return patterns.some(pattern => pattern.dependsOnCharacterData);
520 } 531 }
521 532
522 function ElemHideEmulation(addSelectorsFunc, hideElemsFunc) 533 function ElemHideEmulation(addSelectorsFunc, hideElemsFunc)
523 { 534 {
524 this.document = document; 535 this.document = document;
525 this.addSelectorsFunc = addSelectorsFunc; 536 this.addSelectorsFunc = addSelectorsFunc;
526 this.hideElemsFunc = hideElemsFunc; 537 this.hideElemsFunc = hideElemsFunc;
527 this.observer = new MutationObserver(this.observe.bind(this)); 538 this.observer = new MutationObserver(this.observe.bind(this));
539 this.useInlineStyles = true;
528 } 540 }
529 541
530 ElemHideEmulation.prototype = { 542 ElemHideEmulation.prototype = {
531 isSameOrigin(stylesheet) 543 isSameOrigin(stylesheet)
532 { 544 {
533 try 545 try
534 { 546 {
535 return new URL(stylesheet.href).origin == this.document.location.origin; 547 return new URL(stylesheet.href).origin == this.document.location.origin;
536 } 548 }
537 catch (e) 549 catch (e)
(...skipping 107 matching lines...) Expand 10 before | Expand all | Expand 10 after
645 if (mutations && patterns.some(pattern => pattern.dependsOnStylesAndDOM)) 657 if (mutations && patterns.some(pattern => pattern.dependsOnStylesAndDOM))
646 stylesheets = this.document.styleSheets; 658 stylesheets = this.document.styleSheets;
647 659
648 for (let stylesheet of stylesheets || []) 660 for (let stylesheet of stylesheets || [])
649 { 661 {
650 // Explicitly ignore third-party stylesheets to ensure consistent behavior 662 // Explicitly ignore third-party stylesheets to ensure consistent behavior
651 // between Firefox and Chrome. 663 // between Firefox and Chrome.
652 if (!this.isSameOrigin(stylesheet)) 664 if (!this.isSameOrigin(stylesheet))
653 continue; 665 continue;
654 666
655 let rules = stylesheet.cssRules; 667 let rules;
668 try
669 {
670 rules = stylesheet.cssRules;
671 }
672 catch (e)
673 {
674 // On Firefox, there is a chance that an InvalidAccessError
675 // get thrown when accessing cssRules. Just skip the stylesheet
676 // in that case.
677 // See https://searchfox.org/mozilla-central/rev/f65d7528e34ef1a7665b4a1 a7b7cdb1388fcd3aa/layout/style/StyleSheet.cpp#699
678 continue;
679 }
680
656 if (!rules) 681 if (!rules)
657 continue; 682 continue;
658 683
659 for (let rule of rules) 684 for (let rule of rules)
660 { 685 {
661 if (rule.type != rule.STYLE_RULE) 686 if (rule.type != rule.STYLE_RULE)
662 continue; 687 continue;
663 688
664 cssStyles.push(stringifyStyle(rule)); 689 cssStyles.push(stringifyStyle(rule));
665 } 690 }
(...skipping 21 matching lines...) Expand all
687 712
688 pattern = patterns.shift(); 713 pattern = patterns.shift();
689 714
690 generator = evaluate(pattern.selectors, 0, "", 715 generator = evaluate(pattern.selectors, 0, "",
691 this.document, cssStyles); 716 this.document, cssStyles);
692 } 717 }
693 for (let selector of generator) 718 for (let selector of generator)
694 { 719 {
695 if (selector != null) 720 if (selector != null)
696 { 721 {
697 if (pattern.isSelectorHidingOnlyPattern()) 722 if (!this.useInlineStyles ||
723 pattern.isSelectorHidingOnlyPattern())
698 { 724 {
699 selectors.push(selector); 725 selectors.push(selector);
700 selectorFilters.push(pattern.text); 726 selectorFilters.push(pattern.text);
701 } 727 }
702 else 728 else
703 { 729 {
704 for (let element of this.document.querySelectorAll(selector)) 730 for (let element of this.document.querySelectorAll(selector))
705 { 731 {
706 elements.push(element); 732 elements.push(element);
707 elementFilters.push(pattern.text); 733 elementFilters.push(pattern.text);
(...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after
759 this.queueFiltering(params.stylesheets, params.mutations); 785 this.queueFiltering(params.stylesheets, params.mutations);
760 } 786 }
761 }; 787 };
762 788
763 if (this._scheduledProcessing) 789 if (this._scheduledProcessing)
764 { 790 {
765 if (!stylesheets && !mutations) 791 if (!stylesheets && !mutations)
766 { 792 {
767 this._scheduledProcessing = {}; 793 this._scheduledProcessing = {};
768 } 794 }
769 else 795 else if (this._scheduledProcessing.stylesheets ||
796 this._scheduledProcessing.mutations)
770 { 797 {
771 if (stylesheets) 798 if (stylesheets)
772 { 799 {
773 if (!this._scheduledProcessing.stylesheets) 800 if (!this._scheduledProcessing.stylesheets)
774 this._scheduledProcessing.stylesheets = []; 801 this._scheduledProcessing.stylesheets = [];
775 this._scheduledProcessing.stylesheets.push(...stylesheets); 802 this._scheduledProcessing.stylesheets.push(...stylesheets);
776 } 803 }
777 if (mutations) 804 if (mutations)
778 { 805 {
779 if (!this._scheduledProcessing.mutations) 806 if (!this._scheduledProcessing.mutations)
(...skipping 16 matching lines...) Expand all
796 this._scheduledProcessing = null; 823 this._scheduledProcessing = null;
797 this._addSelectors(params.stylesheets, params.mutations, completion); 824 this._addSelectors(params.stylesheets, params.mutations, completion);
798 }, 825 },
799 MIN_INVOCATION_INTERVAL - (performance.now() - this._lastInvocation)); 826 MIN_INVOCATION_INTERVAL - (performance.now() - this._lastInvocation));
800 } 827 }
801 else if (this.document.readyState == "loading") 828 else if (this.document.readyState == "loading")
802 { 829 {
803 this._scheduledProcessing = {stylesheets, mutations}; 830 this._scheduledProcessing = {stylesheets, mutations};
804 let handler = () => 831 let handler = () =>
805 { 832 {
806 document.removeEventListener("DOMContentLoaded", handler); 833 this.document.removeEventListener("DOMContentLoaded", handler);
807 let params = Object.assign({}, this._scheduledProcessing); 834 let params = Object.assign({}, this._scheduledProcessing);
808 this._filteringInProgress = true; 835 this._filteringInProgress = true;
809 this._scheduledProcessing = null; 836 this._scheduledProcessing = null;
810 this._addSelectors(params.stylesheets, params.mutations, completion); 837 this._addSelectors(params.stylesheets, params.mutations, completion);
811 }; 838 };
812 document.addEventListener("DOMContentLoaded", handler); 839 this.document.addEventListener("DOMContentLoaded", handler);
813 } 840 }
814 else 841 else
815 { 842 {
816 this._filteringInProgress = true; 843 this._filteringInProgress = true;
817 this._addSelectors(stylesheets, mutations, completion); 844 this._addSelectors(stylesheets, mutations, completion);
818 } 845 }
819 }, 846 },
820 847
821 onLoad(event) 848 onLoad(event)
822 { 849 {
(...skipping 28 matching lines...) Expand all
851 characterData: shouldObserveCharacterData(this.patterns), 878 characterData: shouldObserveCharacterData(this.patterns),
852 subtree: true 879 subtree: true
853 } 880 }
854 ); 881 );
855 this.document.addEventListener("load", this.onLoad.bind(this), true); 882 this.document.addEventListener("load", this.onLoad.bind(this), true);
856 } 883 }
857 } 884 }
858 }; 885 };
859 886
860 exports.ElemHideEmulation = ElemHideEmulation; 887 exports.ElemHideEmulation = ElemHideEmulation;
LEFTRIGHT

Powered by Google App Engine
This is Rietveld