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

Delta Between Two Patch Sets: include.preload.js

Issue 29670575: Issue 5899 - Use CSS attribute selectors for collapsing media elements (Closed) Base URL: https://hg.adblockplus.org/adblockpluschrome/
Left Patch Set: Created Jan. 16, 2018, 10:28 a.m.
Right Patch Set: Compare child name directly Created April 19, 2018, 9: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 | lib/cssInjection.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 let {splitSelector} = require("common"); 20 let {splitSelector} = require("./adblockpluscore/lib/common");
21 let {ElemHideEmulation} = require("content_elemHideEmulation"); 21 let {ElemHideEmulation} =
22 require("./adblockpluscore/lib/content/elemHideEmulation");
22 23
23 // This variable is also used by our other content scripts. 24 // This variable is also used by our other content scripts.
24 let elemhide; 25 let elemhide;
25 26
26 const typeMap = new Map([ 27 const typeMap = new Map([
27 ["img", "IMAGE"], 28 ["img", "IMAGE"],
28 ["input", "IMAGE"], 29 ["input", "IMAGE"],
29 ["picture", "IMAGE"], 30 ["picture", "IMAGE"],
30 ["audio", "MEDIA"], 31 ["audio", "MEDIA"],
31 ["video", "MEDIA"], 32 ["video", "MEDIA"],
32 ["frame", "SUBDOCUMENT"], 33 ["frame", "SUBDOCUMENT"],
33 ["iframe", "SUBDOCUMENT"], 34 ["iframe", "SUBDOCUMENT"],
34 ["object", "OBJECT"], 35 ["object", "OBJECT"],
35 ["embed", "OBJECT"] 36 ["embed", "OBJECT"]
36 ]); 37 ]);
37 38
38 let collapsedElements = new WeakMap(); 39 let collapsingSelectors = new Set();
Manish Jethani 2018/01/16 10:47:27 A weak map of collapsed elements to their original
39 40
40 function getURLsFromObjectElement(element) 41 function getURLsFromObjectElement(element)
41 { 42 {
42 let url = element.getAttribute("data"); 43 let url = element.getAttribute("data");
43 if (url) 44 if (url)
44 return [url]; 45 return [url];
45 46
46 for (let child of element.children) 47 for (let child of element.children)
47 { 48 {
48 if (child.localName != "param") 49 if (child.localName != "param")
(...skipping 45 matching lines...) Expand 10 before | Expand all | Expand 10 after
94 if (child.localName == "source" || child.localName == "track") 95 if (child.localName == "source" || child.localName == "track")
95 urls.push(...getURLsFromAttributes(child)); 96 urls.push(...getURLsFromAttributes(child));
96 } 97 }
97 98
98 if (element.poster) 99 if (element.poster)
99 urls.push(element.poster); 100 urls.push(element.poster);
100 101
101 return urls; 102 return urls;
102 } 103 }
103 104
104 function getURLsFromElement(element, all) 105 function getURLsFromElement(element)
105 { 106 {
106 let urls; 107 let urls;
107 switch (element.localName) 108 switch (element.localName)
108 { 109 {
109 case "object": 110 case "object":
110 urls = getURLsFromObjectElement(element); 111 urls = getURLsFromObjectElement(element);
111 break; 112 break;
112 113
113 case "video": 114 case "video":
114 case "audio": 115 case "audio":
115 case "picture": 116 case "picture":
116 urls = getURLsFromMediaElement(element); 117 urls = getURLsFromMediaElement(element);
117 break; 118 break;
118 119
119 default: 120 default:
120 urls = getURLsFromAttributes(element); 121 urls = getURLsFromAttributes(element);
121 break; 122 break;
122 } 123 }
123 124
124 if (all)
125 return urls;
126
127 for (let i = 0; i < urls.length; i++) 125 for (let i = 0; i < urls.length; i++)
128 { 126 {
129 if (/^(?!https?:)[\w-]+:/i.test(urls[i])) 127 if (/^(?!https?:)[\w-]+:/i.test(urls[i]))
130 urls.splice(i--, 1); 128 urls.splice(i--, 1);
131 } 129 }
132 130
133 return urls; 131 return urls;
134 } 132 }
135 133
136 function collapseElement(element) 134 function isCollapsibleMediaElement(element, mediatype)
Manish Jethani 2018/01/16 10:47:27 This is basically what hideElement does, except it
137 { 135 {
138 let value = element.style.getPropertyValue("display"); 136 if (mediatype != "MEDIA")
139 let priority = element.style.getPropertyPriority("display"); 137 return false;
140 if (value != "none" || priority != "important") 138
141 { 139 if (!element.getAttribute("src"))
142 element.style.setProperty("display", "none", "important"); 140 return false;
143 collapsedElements.set(element, {value, priority}); 141
144 } 142 for (let child of element.children)
145 } 143 {
146 144 // If the <video> or <audio> element contains any <source> or <track>
147 function restoreCollapsedElement(element) 145 // children, we cannot address it in CSS by the source URL; in that case we
148 { 146 // don't "collapse" it using a CSS selector but rather hide it directly by
149 let display = collapsedElements.get(element); 147 // setting the style="..." attribute.
150 if (display) 148 if (child.localName == "source" || child.localName == "track")
Manish Jethani 2018/01/16 10:47:27 Restore the original display settings.
151 { 149 return false;
152 element.style.setProperty("display", display.value, display.priority); 150 }
153 collapsedElements.delete(element); 151
152 return true;
153 }
154
155 function collapseMediaElement(element, srcValue)
156 {
157 if (!srcValue)
158 return;
159
160 let selector = element.localName + "[src=" + CSS.escape(srcValue) + "]";
161
162 // Adding selectors is expensive so do it only if we really have a new
163 // selector.
164 if (!collapsingSelectors.has(selector))
165 {
166 collapsingSelectors.add(selector);
167 elemhide.addSelectors([selector], null, "collapsing", true);
154 } 168 }
155 } 169 }
156 170
157 function hideElement(element) 171 function hideElement(element)
158 { 172 {
159 function doHide() 173 function doHide()
160 { 174 {
161 let propertyName = "display"; 175 let propertyName = "display";
162 let propertyValue = "none"; 176 let propertyValue = "none";
163 if (element.localName == "frame") 177 if (element.localName == "frame")
(...skipping 16 matching lines...) Expand all
180 } 194 }
181 ); 195 );
182 } 196 }
183 197
184 function checkCollapse(element) 198 function checkCollapse(element)
185 { 199 {
186 let mediatype = typeMap.get(element.localName); 200 let mediatype = typeMap.get(element.localName);
187 if (!mediatype) 201 if (!mediatype)
188 return; 202 return;
189 203
190 let urls = getURLsFromElement(element, mediatype == "MEDIA"); 204 let urls = getURLsFromElement(element);
Manish Jethani 2018/01/16 10:47:27 We have to pass true here as the second argument,
191 if (urls.length == 0) 205 if (urls.length == 0)
192 return; 206 return;
207
208 let collapsibleMediaElement = isCollapsibleMediaElement(element, mediatype);
209
210 // Save the value of the src attribute because it can change between now and
211 // when we get the response from the background page.
212 let srcValue = collapsibleMediaElement ? element.getAttribute("src") : null;
193 213
194 browser.runtime.sendMessage( 214 browser.runtime.sendMessage(
195 { 215 {
196 type: "filters.collapse", 216 type: "filters.collapse",
197 urls, 217 urls,
198 mediatype, 218 mediatype,
199 baseURL: document.location.href 219 baseURL: document.location.href
200 }, 220 },
201
202 collapse => 221 collapse =>
203 { 222 {
204 if (mediatype == "MEDIA") 223 if (collapse)
205 { 224 {
206 if (collapse) 225 if (collapsibleMediaElement)
Manish Jethani 2018/01/16 10:47:27 I'm distinguishing "collapsing" from "hiding" here
207 collapseElement(element); 226 collapseMediaElement(element, srcValue);
208 else 227 else
209 restoreCollapsedElement(element); 228 hideElement(element);
210 }
211 else if (collapse)
212 {
213 hideElement(element);
214 } 229 }
215 } 230 }
216 ); 231 );
217 } 232 }
218 233
219 function checkSitekey() 234 function checkSitekey()
220 { 235 {
221 let attr = document.documentElement.getAttribute("data-adblockkey"); 236 let attr = document.documentElement.getAttribute("data-adblockkey");
222 if (attr) 237 if (attr)
223 browser.runtime.sendMessage({type: "filters.addKey", token: attr}); 238 browser.runtime.sendMessage({type: "filters.addKey", token: attr});
(...skipping 144 matching lines...) Expand 10 before | Expand all | Expand 10 after
368 { 383 {
369 document.removeEventListener("DOMContentLoaded", this.trace); 384 document.removeEventListener("DOMContentLoaded", this.trace);
370 this.observer.disconnect(); 385 this.observer.disconnect();
371 clearTimeout(this.timeout); 386 clearTimeout(this.timeout);
372 } 387 }
373 }; 388 };
374 389
375 function ElemHide() 390 function ElemHide()
376 { 391 {
377 this.shadow = this.createShadowTree(); 392 this.shadow = this.createShadowTree();
378 this.style = null; 393 this.styles = new Map();
379 this.tracer = null; 394 this.tracer = null;
380 this.inject = true; 395 this.inline = true;
381 this.emulatedPatterns = null; 396 this.inlineEmulated = true;
382 397
383 this.elemHideEmulation = new ElemHideEmulation( 398 this.elemHideEmulation = new ElemHideEmulation(
384 this.addSelectors.bind(this), 399 this.addSelectors.bind(this),
385 this.hideElements.bind(this) 400 this.hideElements.bind(this)
386 ); 401 );
387 } 402 }
388 ElemHide.prototype = { 403 ElemHide.prototype = {
389 selectorGroupSize: 200, 404 selectorGroupSize: 1024,
390 405
391 createShadowTree() 406 createShadowTree()
392 { 407 {
393 // Use Shadow DOM if available as to not mess with with web pages that 408 // Use Shadow DOM if available as to not mess with with web pages that
394 // rely on the order of their own <style> tags (#309). However, creating 409 // rely on the order of their own <style> tags (#309). However, creating
395 // a shadow root breaks running CSS transitions. So we have to create 410 // a shadow root breaks running CSS transitions. So we have to create
396 // the shadow root before transistions might start (#452). 411 // the shadow root before transistions might start (#452).
397 if (!("createShadowRoot" in document.documentElement)) 412 if (!("createShadowRoot" in document.documentElement))
398 return null; 413 return null;
399 414
415 // Both Firefox and Chrome 66+ support user style sheets, so we can avoid
416 // creating an unnecessary shadow root on these platforms.
417 let match = /\bChrome\/(\d+)/.exec(navigator.userAgent);
418 if (!match || match[1] >= 66)
419 return null;
420
400 // Using shadow DOM causes issues on some Google websites, 421 // Using shadow DOM causes issues on some Google websites,
401 // including Google Docs, Gmail and Blogger (#1770, #2602, #2687). 422 // including Google Docs, Gmail and Blogger (#1770, #2602, #2687).
402 if (/\.(?:google|blogger)\.com$/.test(document.domain)) 423 if (/\.(?:google|blogger)\.com$/.test(document.domain))
403 return null; 424 return null;
404 425
405 // Finally since some users have both AdBlock and Adblock Plus installed we 426 // Finally since some users have both AdBlock and Adblock Plus installed we
406 // have to consider how the two extensions interact. For example we want to 427 // have to consider how the two extensions interact. For example we want to
407 // avoid creating the shadowRoot twice. 428 // avoid creating the shadowRoot twice.
408 let shadow = document.documentElement.shadowRoot || 429 let shadow = document.documentElement.shadowRoot ||
409 document.documentElement.createShadowRoot(); 430 document.documentElement.createShadowRoot();
410 shadow.appendChild(document.createElement("shadow")); 431 shadow.appendChild(document.createElement("content"));
411 432
412 return shadow; 433 return shadow;
413 }, 434 },
414 435
415 injectSelectors(selectors, filters) 436 addSelectorsInline(selectors, groupName, appendOnly = false)
416 { 437 {
417 if (!this.style) 438 let style = this.styles.get(groupName);
439
440 if (style && !appendOnly)
441 {
442 while (style.sheet.cssRules.length > 0)
443 style.sheet.deleteRule(0);
444 }
445
446 if (selectors.length == 0)
447 return;
448
449 if (!style)
418 { 450 {
419 // Create <style> element lazily, only if we add styles. Add it to 451 // Create <style> element lazily, only if we add styles. Add it to
420 // the shadow DOM if possible. Otherwise fallback to the <head> or 452 // the shadow DOM if possible. Otherwise fallback to the <head> or
421 // <html> element. If we have injected a style element before that 453 // <html> element. If we have injected a style element before that
422 // has been removed (the sheet property is null), create a new one. 454 // has been removed (the sheet property is null), create a new one.
423 this.style = document.createElement("style"); 455 style = document.createElement("style");
424 (this.shadow || document.head || 456 (this.shadow || document.head ||
425 document.documentElement).appendChild(this.style); 457 document.documentElement).appendChild(style);
426 458
427 // It can happen that the frame already navigated to a different 459 // It can happen that the frame already navigated to a different
428 // document while we were waiting for the background page to respond. 460 // document while we were waiting for the background page to respond.
429 // In that case the sheet property will stay null, after addind the 461 // In that case the sheet property will stay null, after addind the
430 // <style> element to the shadow DOM. 462 // <style> element to the shadow DOM.
431 if (!this.style.sheet) 463 if (!style.sheet)
432 return; 464 return;
465
466 this.styles.set(groupName, style);
433 } 467 }
434 468
435 // If using shadow DOM, we have to add the ::content pseudo-element 469 // If using shadow DOM, we have to add the ::content pseudo-element
436 // before each selector, in order to match elements within the 470 // before each selector, in order to match elements within the
437 // insertion point. 471 // insertion point.
438 let preparedSelectors = []; 472 let preparedSelectors = [];
439 if (this.shadow) 473 if (this.shadow)
440 { 474 {
441 for (let selector of selectors) 475 for (let selector of selectors)
442 { 476 {
443 let subSelectors = splitSelector(selector); 477 let subSelectors = splitSelector(selector);
444 for (let subSelector of subSelectors) 478 for (let subSelector of subSelectors)
445 preparedSelectors.push("::content " + subSelector); 479 preparedSelectors.push("::content " + subSelector);
446 } 480 }
447 } 481 }
448 else 482 else
449 { 483 {
450 preparedSelectors = selectors; 484 preparedSelectors = selectors;
451 } 485 }
452 486
453 // Safari only allows 8192 primitive selectors to be injected at once[1], we 487 // Chromium's Blink engine supports only up to 8,192 simple selectors, and
454 // therefore chunk the inserted selectors into groups of 200 to be safe. 488 // even fewer compound selectors, in a rule. The exact number of selectors
455 // (Chrome also has a limit, larger... but we're not certain exactly what it 489 // that would work depends on their sizes (e.g. "#foo .bar" has a
456 // is! Edge apparently has no such limit.) 490 // size of 2). Since we don't know the sizes of the selectors here, we
457 // [1] - https://github.com/WebKit/webkit/blob/1cb2227f6b2a1035f7bdc46e5ab69 debb75fc1de/Source/WebCore/css/RuleSet.h#L68 491 // simply split them into groups of 1,024, based on the reasonable
492 // assumption that the average selector won't have a size greater than 8.
493 // The alternative would be to calculate the sizes of the selectors and
494 // divide them up accordingly, but this approach is more efficient and has
495 // worked well in practice. In theory this could still lead to some
496 // selectors not working on Chromium, but it is highly unlikely.
497 // See issue #6298 and https://crbug.com/804179
458 for (let i = 0; i < preparedSelectors.length; i += this.selectorGroupSize) 498 for (let i = 0; i < preparedSelectors.length; i += this.selectorGroupSize)
459 { 499 {
460 let selector = preparedSelectors.slice( 500 let selector = preparedSelectors.slice(
461 i, i + this.selectorGroupSize 501 i, i + this.selectorGroupSize
462 ).join(", "); 502 ).join(", ");
463 this.style.sheet.insertRule(selector + "{display: none !important;}", 503 style.sheet.insertRule(selector + "{display: none !important;}",
464 this.style.sheet.cssRules.length); 504 style.sheet.cssRules.length);
465 } 505 }
466 }, 506 },
467 507
468 addSelectors(selectors, filters) 508 addSelectors(selectors, filters, groupName = "emulated", appendOnly = false)
469 { 509 {
470 if (selectors.length == 0) 510 if (this.inline || this.inlineEmulated)
471 return;
472
473 if (this.inject)
474 { 511 {
475 // Insert the style rules inline if we have been instructed by the 512 // Insert the style rules inline if we have been instructed by the
476 // background page to do so. This is usually the case, except on platforms 513 // background page to do so. This is usually the case, except on platforms
477 // that do support user stylesheets via the browser.tabs.insertCSS API 514 // that do support user stylesheets via the browser.tabs.insertCSS API
478 // (Firefox 53 onwards for now and possibly Chrome in the near future). 515 // (Firefox 53 onwards for now and possibly Chrome in the near future).
479 // Once all supported platforms have implemented this API, we can remove 516 // Once all supported platforms have implemented this API, we can remove
480 // the code below. See issue #5090. 517 // the code below. See issue #5090.
481 // Related Chrome and Firefox issues: 518 // Related Chrome and Firefox issues:
482 // https://bugs.chromium.org/p/chromium/issues/detail?id=632009 519 // https://bugs.chromium.org/p/chromium/issues/detail?id=632009
483 // https://bugzilla.mozilla.org/show_bug.cgi?id=1310026 520 // https://bugzilla.mozilla.org/show_bug.cgi?id=1310026
484 this.injectSelectors(selectors, filters); 521 this.addSelectorsInline(selectors, groupName, appendOnly);
485 } 522 }
486 else 523 else
487 { 524 {
488 browser.runtime.sendMessage({ 525 browser.runtime.sendMessage({
489 type: "elemhide.injectSelectors", 526 type: "elemhide.injectSelectors",
490 selectors 527 selectors,
528 groupName,
529 appendOnly
491 }); 530 });
492 } 531 }
493 532
494 if (this.tracer) 533 // Only trace selectors that are based directly on hiding filters
534 // (i.e. leave out collapsing selectors).
535 if (this.tracer && groupName != "collapsing")
495 this.tracer.addSelectors(selectors, filters); 536 this.tracer.addSelectors(selectors, filters);
496 }, 537 },
497 538
498 hideElements(elements, filters) 539 hideElements(elements, filters)
499 { 540 {
500 for (let element of elements) 541 for (let element of elements)
501 hideElement(element); 542 hideElement(element);
502 543
503 if (this.tracer) 544 if (this.tracer)
504 { 545 {
505 browser.runtime.sendMessage({ 546 browser.runtime.sendMessage({
506 type: "devtools.traceElemHide", 547 type: "devtools.traceElemHide",
507 selectors: [], 548 selectors: [],
508 filters 549 filters
509 }); 550 });
510 } 551 }
511 }, 552 },
512 553
513 apply() 554 apply()
514 { 555 {
515 browser.runtime.sendMessage({type: "elemhide.getSelectors"}, response => 556 browser.runtime.sendMessage({type: "elemhide.getSelectors"}, response =>
516 { 557 {
517 if (this.tracer) 558 if (this.tracer)
518 this.tracer.disconnect(); 559 this.tracer.disconnect();
519 this.tracer = null; 560 this.tracer = null;
520 561
521 if (this.style && this.style.parentElement)
522 this.style.parentElement.removeChild(this.style);
523 this.style = null;
524
525 if (response.trace) 562 if (response.trace)
526 this.tracer = new ElementHidingTracer(); 563 this.tracer = new ElementHidingTracer();
527 564
528 this.inject = response.inject; 565 this.inline = response.inline;
529 566 this.inlineEmulated = !!response.inlineEmulated;
530 if (this.inject) 567
531 this.addSelectors(response.selectors); 568 if (this.inline)
532 else if (this.tracer) 569 this.addSelectorsInline(response.selectors, "standard");
570
571 if (this.tracer)
533 this.tracer.addSelectors(response.selectors); 572 this.tracer.addSelectors(response.selectors);
573
574 // Prefer CSS selectors for -abp-has and -abp-contains unless the
575 // background page has asked us to use inline styles.
576 this.elemHideEmulation.useInlineStyles = this.inline ||
577 this.inlineEmulated;
534 578
535 this.elemHideEmulation.apply(response.emulatedPatterns); 579 this.elemHideEmulation.apply(response.emulatedPatterns);
536 }); 580 });
537 } 581 }
538 }; 582 };
539 583
540 if (document instanceof HTMLDocument) 584 if (document instanceof HTMLDocument)
541 { 585 {
542 checkSitekey(); 586 checkSitekey();
543 587
544 elemhide = new ElemHide(); 588 elemhide = new ElemHide();
545 elemhide.apply(); 589 elemhide.apply();
546 590
547 document.addEventListener("error", event => 591 document.addEventListener("error", event =>
548 { 592 {
549 checkCollapse(event.target); 593 checkCollapse(event.target);
550 }, true); 594 }, true);
551 595
552 document.addEventListener("load", event => 596 document.addEventListener("load", event =>
553 { 597 {
554 let element = event.target; 598 let element = event.target;
555 if (/^i?frame$/.test(element.localName)) 599 if (/^i?frame$/.test(element.localName))
556 checkCollapse(element); 600 checkCollapse(element);
557 }, true); 601 }, true);
558
559 document.addEventListener("loadstart", event =>
Manish Jethani 2018/01/16 10:47:27 The "loadstart" event is dispatched by VIDEO and A
560 {
561 let element = event.target;
562 if (typeMap.get(element.localName) == "MEDIA")
Manish Jethani 2018/01/16 10:47:27 We have to do this check because IMG and PICTURE e
563 checkCollapse(element);
564 }, true);
565 } 602 }
566 603
567 window.checkCollapse = checkCollapse; 604 window.checkCollapse = checkCollapse;
568 window.elemhide = elemhide; 605 window.elemhide = elemhide;
569 window.typeMap = typeMap; 606 window.typeMap = typeMap;
570 window.getURLsFromElement = getURLsFromElement; 607 window.getURLsFromElement = getURLsFromElement;
LEFTRIGHT

Powered by Google App Engine
This is Rietveld