forked from adblockplus/backup-adblockpluschrome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
include.postload.js
694 lines (603 loc) · 21.8 KB
/
include.postload.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
/*
* This file is part of Adblock Plus <http://adblockplus.org/>,
* Copyright (C) 2006-2014 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/>.
*/
// Click-to-hide stuff
var clickHide_activated = false;
var clickHide_filters = null;
var currentElement = null;
var clickHideFilters = null;
var highlightedElementsSelector = null;
var clickHideFiltersDialog = null;
var lastRightClickEvent = null;
function escapeChar(chr)
{
var code = chr.charCodeAt(0);
// Control characters and leading digits must be escaped based on
// their char code in CSS. Moreover, curly brackets aren't allowed
// in elemhide filters, and therefore must be escaped based on their
// char code as well.
if (code <= 0x1F || code == 0x7F || /[\d\{\}]/.test(chr))
return "\\" + code.toString(16) + " ";
return "\\" + chr;
}
function quote(value)
{
return '"' + value.replace(/["\\\{\}\x00-\x1F\x7F]/g, escapeChar) + '"';
}
function escapeCSS(s)
{
return s.replace(/^[\d\-]|[^\w\-\u0080-\uFFFF]/g, escapeChar);
}
function supportsShadowRoot(element)
{
if (!("createShadowRoot" in element))
return false;
// There are some elements (e.g. <textarea>), which don't
// support author created shadow roots and throw an exception.
var clone = element.cloneNode(false);
try
{
clone.createShadowRoot();
}
catch (e)
{
return false;
}
// There are some elements (e.g. <input>), which support
// author created shadow roots, but ignore insertion points.
var child = document.createTextNode("");
clone.appendChild(child);
var shadow = document.createElement("shadow");
clone.shadowRoot.appendChild(shadow);
return shadow.getDistributedNodes()[0] == child;
}
function highlightElement(element, shadowColor, backgroundColor)
{
unhighlightElement(element);
var originalBoxShadowPriority = element.style.getPropertyPriority("box-shadow");
var originalBackgroundColorPriority = element.style.getPropertyPriority("background-color");
var boxShadow = "inset 0px 0px 5px " + shadowColor;
var highlightWithShadowDOM = function()
{
var style = document.createElement("style");
style.textContent = ":host {" +
"box-shadow:" + boxShadow + " !important;" +
"background-color:" + backgroundColor + " !important;" +
"}";
var root = element.createShadowRoot();
root.appendChild(document.createElement("shadow"));
root.appendChild(style);
element._unhighlight = function()
{
root.removeChild(style);
};
};
var highlightWithStyleAttribute = function()
{
var originalBoxShadow = element.style.getPropertyValue("box-shadow");
var originalBackgroundColor = element.style.getPropertyValue("background-color");
element.style.setProperty("box-shadow", boxShadow, "important");
element.style.setProperty("background-color", backgroundColor, "important");
element._unhighlight = function()
{
this.style.removeProperty("box-shadow");
this.style.setProperty(
"box-shadow",
originalBoxShadow,
originalBoxShadowPriority
);
this.style.removeProperty("background-color");
this.style.setProperty(
"background-color",
originalBackgroundColor,
originalBackgroundColorPriority
);
};
};
// Use shadow DOM if posibble to avoid side effects when the
// web page updates style while highlighted. However, if the
// element has important styles we can't override them with shadow DOM.
if (supportsShadowRoot(element) && originalBoxShadowPriority != "important" &&
originalBackgroundColorPriority != "important")
highlightWithShadowDOM();
else
highlightWithStyleAttribute();
}
function unhighlightElement(element)
{
if ("_unhighlight" in element)
{
element._unhighlight();
delete element._unhighlight;
}
}
// Highlight elements according to selector string. This would include
// all elements that would be affected by proposed filters.
function highlightElements(selectorString) {
unhighlightElements();
var highlightedElements = document.querySelectorAll(selectorString);
highlightedElementsSelector = selectorString;
for(var i = 0; i < highlightedElements.length; i++)
highlightElement(highlightedElements[i], "#fd6738", "#f6e1e5");
}
// Unhighlight all elements, including those that would be affected by
// the proposed filters
function unhighlightElements() {
if (highlightedElementsSelector)
{
Array.prototype.forEach.call(
document.querySelectorAll(highlightedElementsSelector),
unhighlightElement
);
highlightedElementsSelector = null;
}
}
// Gets the absolute position of an element by walking up the DOM tree,
// adding up offsets.
// I hope there's a better way because it just seems absolutely stupid
// that the DOM wouldn't have a direct way to get this, given that it
// has hundreds and hundreds of other methods that do random junk.
function getAbsolutePosition(elt) {
var l = 0;
var t = 0;
for(; elt; elt = elt.offsetParent) {
l += elt.offsetLeft;
t += elt.offsetTop;
}
return [l, t];
}
// Adds an overlay to an element, which is probably a Flash object
function addElementOverlay(elt) {
// If this element is enclosed in an object tag, we prefer to block that instead
if(!elt)
return null;
// If element doesn't have at least one of class name, ID or URL, give up
// because we don't know how to construct a filter rule for it
var url = getElementURL(elt);
if(!elt.className && !elt.id && !url)
return;
// If the element isn't rendered (since its or one of its ancestor's
// "display" property is "none"), the overlay wouldn't match the element.
if (!elt.offsetParent)
return;
var thisStyle = getComputedStyle(elt, null);
var overlay = document.createElement('div');
overlay.prisoner = elt;
overlay.prisonerURL = url;
overlay.className = "__adblockplus__overlay";
overlay.setAttribute('style', 'opacity:0.4; background-color:#ffffff; display:inline-box; ' + 'width:' + thisStyle.width + '; height:' + thisStyle.height + '; position:absolute; overflow:hidden; -webkit-box-sizing:border-box;');
var pos = getAbsolutePosition(elt);
overlay.style.left = pos[0] + "px";
overlay.style.top = pos[1] + "px";
if (thisStyle.position != "static")
overlay.style.zIndex = thisStyle.zIndex;
else
overlay.style.zIndex = getComputedStyle(elt.offsetParent).zIndex;
// elt.parentNode.appendChild(overlay, elt);
document.body.appendChild(overlay);
return overlay;
}
// Show dialog asking user whether she wants to add the proposed filters derived
// from selected page element
function clickHide_showDialog(left, top, filters)
{
// If we are already selecting, abort now
if (clickHide_activated || clickHideFiltersDialog)
clickHide_deactivate(true);
clickHide_filters = filters;
clickHideFiltersDialog = document.createElement("iframe");
clickHideFiltersDialog.src = ext.getURL("block.html");
clickHideFiltersDialog.setAttribute("style", "position: fixed !important; visibility: hidden; display: block !important; border: 0px !important;");
clickHideFiltersDialog.style.WebkitBoxShadow = "5px 5px 20px rgba(0,0,0,0.5)";
clickHideFiltersDialog.style.zIndex = 0x7FFFFFFF;
// Position in upper-left all the time
clickHideFiltersDialog.style.left = "50px";
clickHideFiltersDialog.style.top = "50px";
// Make dialog partly transparent when mouse isn't over it so user has a better
// view of what's going to be blocked
clickHideFiltersDialog.onmouseout = function()
{
if (clickHideFiltersDialog)
clickHideFiltersDialog.style.setProperty("opacity", "0.7");
}
clickHideFiltersDialog.onmouseover = function()
{
if (clickHideFiltersDialog)
clickHideFiltersDialog.style.setProperty("opacity", "1.0");
}
document.body.appendChild(clickHideFiltersDialog);
}
// Turn on the choose element to create filter thing
function clickHide_activate() {
if(document == null)
return;
// If we are already selecting, abort now
if (clickHide_activated || clickHideFiltersDialog)
clickHide_deactivate();
// Add overlays for elements with URLs so user can easily click them
var elts = document.querySelectorAll('object,embed,img,iframe');
for(var i=0; i<elts.length; i++)
addElementOverlay(elts[i]);
clickHide_activated = true;
document.addEventListener("mouseover", clickHide_mouseOver, true);
document.addEventListener("mouseout", clickHide_mouseOut, true);
document.addEventListener("click", clickHide_mouseClick, true);
document.addEventListener("keydown", clickHide_keyDown, true);
}
// Called when user has clicked on something and we are waiting for confirmation
// on whether the user actually wants these filters
function clickHide_rulesPending() {
clickHide_activated = false;
document.removeEventListener("mouseover", clickHide_mouseOver, true);
document.removeEventListener("mouseout", clickHide_mouseOut, true);
document.removeEventListener("click", clickHide_mouseClick, true);
document.removeEventListener("keydown", clickHide_keyDown, true);
}
// Turn off click-to-hide
function clickHide_deactivate(keepOverlays)
{
if (clickHideFiltersDialog)
{
document.body.removeChild(clickHideFiltersDialog);
clickHideFiltersDialog = null;
}
clickHide_activated = false;
clickHide_filters = null;
if(!document)
return; // This can happen inside a nuked iframe...I think
document.removeEventListener("mouseover", clickHide_mouseOver, true);
document.removeEventListener("mouseout", clickHide_mouseOut, true);
document.removeEventListener("click", clickHide_mouseClick, true);
document.removeEventListener("keydown", clickHide_keyDown, true);
if (!keepOverlays)
{
if (currentElement) {
currentElement.removeEventListener("contextmenu", clickHide_elementClickHandler, true);
unhighlightElements();
unhighlightElement(currentElement);
currentElement = null;
clickHideFilters = null;
}
unhighlightElements();
var overlays = document.getElementsByClassName("__adblockplus__overlay");
while (overlays.length > 0)
overlays[0].parentNode.removeChild(overlays[0]);
}
}
function clickHide_elementClickHandler(ev) {
ev.preventDefault();
ev.stopPropagation();
clickHide_mouseClick(ev);
}
// Hovering over an element so highlight it
function clickHide_mouseOver(e)
{
if (clickHide_activated == false)
return;
var target = e.target;
while (target.parentNode && !(target.id || target.className || target.src || /:.+:/.test(target.getAttribute("style"))))
target = target.parentNode;
if (target == document.documentElement || target == document.body)
target = null;
if (target && target instanceof HTMLElement)
{
currentElement = target;
highlightElement(target, "#d6d84b", "#f8fa47");
target.addEventListener("contextmenu", clickHide_elementClickHandler, true);
}
}
// No longer hovering over this element so unhighlight it
function clickHide_mouseOut(e)
{
if (!clickHide_activated || !currentElement)
return;
unhighlightElement(currentElement);
currentElement.removeEventListener("contextmenu", clickHide_elementClickHandler, true);
}
// Selects the currently hovered-over filter or cancels selection
function clickHide_keyDown(e)
{
if (!e.ctrlKey && !e.altKey && !e.shiftKey && e.keyCode == 13 /*DOM_VK_RETURN*/)
clickHide_mouseClick(e);
else if (!e.ctrlKey && !e.altKey && !e.shiftKey && e.keyCode == 27 /*DOM_VK_ESCAPE*/)
{
ext.backgroundPage.sendMessage(
{
type: "forward",
payload:
{
type: "clickhide-deactivate"
}
});
e.preventDefault();
e.stopPropagation();
}
}
// When the user clicks, the currentElement is the one we want.
// We should have ABP rules ready for when the
// popup asks for them.
function clickHide_mouseClick(e)
{
if (!currentElement || !clickHide_activated)
return;
var elt = currentElement;
var url = null;
if (currentElement.classList.contains("__adblockplus__overlay"))
{
elt = currentElement.prisoner;
url = currentElement.prisonerURL;
}
else if (elt.src)
url = elt.src;
clickHideFilters = new Array();
selectorList = new Array();
var addSelector = function(selector)
{
clickHideFilters.push(document.domain + "##" + selector);
selectorList.push(selector);
};
if (elt.id)
addSelector("#" + escapeCSS(elt.id));
if (elt.classList.length > 0)
{
var selector = "";
for (var i = 0; i < elt.classList.length; i++)
selector += "." + escapeCSS(elt.classList[i]);
addSelector(selector);
}
if (url)
{
var src = elt.getAttribute("src");
var selector = src && escapeCSS(elt.localName) + '[src=' + quote(src) + ']';
if (/^https?:/i.test(url))
{
clickHideFilters.push(url.replace(/^[\w\-]+:\/+(?:www\.)?/, "||"));
if (selector)
selectorList.push(selector);
}
else if (selector)
addSelector(selector);
}
// restore the original style, before generating the fallback filter that
// will include the style, and to prevent highlightElements from saving those
unhighlightElement(currentElement);
// as last resort, create a filter based on inline styles
if (clickHideFilters.length == 0)
{
var style = elt.getAttribute("style");
if (style)
addSelector(escapeCSS(elt.localName) + '[style=' + quote(style) + ']');
}
// Show popup
clickHide_showDialog(e.clientX, e.clientY, clickHideFilters);
// Highlight the elements specified by selector in yellow
if (selectorList.length > 0)
highlightElements(selectorList.join(","));
// Now, actually highlight the element the user clicked on in red
highlightElement(currentElement, "#fd1708", "#f6a1b5");
// Make sure the browser doesn't handle this click
e.preventDefault();
e.stopPropagation();
}
// Extracts source URL from an IMG, OBJECT, EMBED, or IFRAME
function getElementURL(elt) {
// Check children of object nodes for "param" nodes with name="movie" that specify a URL
// in value attribute
var url;
if(elt.localName.toUpperCase() == "OBJECT" && !(url = elt.getAttribute("data"))) {
// No data attribute, look in PARAM child tags for a URL for the swf file
var params = elt.querySelectorAll("param[name=\"movie\"]");
// This OBJECT could contain an EMBED we already nuked, in which case there's no URL
if(params[0])
url = params[0].getAttribute("value");
else {
params = elt.querySelectorAll("param[name=\"src\"]");
if(params[0])
url = params[0].getAttribute("value");
}
if (url)
url = resolveURL(url);
} else if(!url) {
url = elt.src || elt.href;
}
return url;
}
// This function Copyright (c) 2008 Jeni Tennison, from jquery.uri.js
// and licensed under the MIT license. See jquery-*.min.js for details.
function removeDotSegments(u) {
var r = '', m = [];
if (/\./.test(u)) {
while (u !== undefined && u !== '') {
if (u === '.' || u === '..') {
u = '';
} else if (/^\.\.\//.test(u)) { // starts with ../
u = u.substring(3);
} else if (/^\.\//.test(u)) { // starts with ./
u = u.substring(2);
} else if (/^\/\.(\/|$)/.test(u)) { // starts with /./ or consists of /.
u = '/' + u.substring(3);
} else if (/^\/\.\.(\/|$)/.test(u)) { // starts with /../ or consists of /..
u = '/' + u.substring(4);
r = r.replace(/\/?[^\/]+$/, '');
} else {
m = u.match(/^(\/?[^\/]*)(\/.*)?$/);
u = m[2];
r = r + m[1];
}
}
return r;
} else {
return u;
}
}
// In Chrome 37-40, the document_end content script (this one) runs properly, while the
// document_start content scripts (that defines ext) might not. Check whether variable ext
// exists before continuing to avoid "Uncaught ReferenceError: ext is not defined".
// See https://crbug.com/416907
if ("ext" in window && document instanceof HTMLDocument)
{
// Use a contextmenu handler to save the last element the user right-clicked on.
// To make things easier, we actually save the DOM event.
// We have to do this because the contextMenu API only provides a URL, not the actual
// DOM element.
document.addEventListener('contextmenu', function(e) {
lastRightClickEvent = e;
}, true);
document.addEventListener("click", function(event)
{
// Ignore right-clicks
if (event.button == 2)
return;
// Search the link associated with the click
var link = event.target;
while (link && !(link instanceof HTMLAnchorElement))
link = link.parentNode;
if (!link || link.protocol != "abp:")
return;
// This is our link - make sure the browser doesn't handle it
event.preventDefault();
event.stopPropagation();
var linkTarget = link.href;
if (!/^abp:\/*subscribe\/*\?(.*)/i.test(linkTarget)) /**/
return;
// Decode URL parameters
var params = RegExp.$1.split("&");
var title = null;
var url = null;
for (var i = 0; i < params.length; i++)
{
var parts = params[i].split("=", 2);
if (parts.length != 2 || !/\S/.test(parts[1]))
continue;
switch (parts[0])
{
case "title":
title = decodeURIComponent(parts[1]);
break;
case "location":
url = decodeURIComponent(parts[1]);
break;
}
}
if (!url)
return;
// Default title to the URL
if (!title)
title = url;
// Trim spaces in title and URL
title = title.replace(/^\s+/, "").replace(/\s+$/, "");
url = url.replace(/^\s+/, "").replace(/\s+$/, "");
if (!/^(https?|ftp):/.test(url))
return;
ext.backgroundPage.sendMessage({
type: "add-subscription",
title: title,
url: url
});
}, true);
ext.onMessage.addListener(function(msg, sender, sendResponse)
{
switch (msg.type)
{
case "get-clickhide-state":
sendResponse({active: clickHide_activated});
break;
case "clickhide-activate":
clickHide_activate();
break;
case "clickhide-deactivate":
clickHide_deactivate();
break;
case "clickhide-new-filter":
// The request is received by all frames, so ignore it if we're not the frame the
// user right-clicked in
if(!lastRightClickEvent)
return;
// We hope the URL we are given is the same as the one in the element referenced
// by lastRightClickEvent.target. If not, we just discard
var target = lastRightClickEvent.target;
var url = target.src;
// If we don't have the element with a src URL same as the filter, look for it.
// Chrome's context menu API is terrible. Why can't it give us the friggin' element
// to start with?
if(msg.filter !== url)
{
// Grab all elements with a src attribute.
// This won't work for all object/embed tags, but the context menu API doesn't
// work on those, so we're OK for now.
var elts = document.querySelectorAll('[src]');
for(var i=0; i<elts.length; i++) {
url = elts[i].src;
if(msg.filter === url)
{
// This is hopefully our element. In case of multiple elements
// with the same src, only one will be highlighted.
target = elts[i];
break;
}
}
}
// Following test will be true if we found the element with the filter URL
if(msg.filter === url)
{
// This request would have come from the chrome.contextMenu handler, so we
// simulate the user having chosen the element to get rid of via the usual means.
clickHide_activated = true;
// FIXME: clickHideFilters is erased in clickHide_mouseClick anyway, so why set it?
clickHideFilters = [msg.filter];
// Coerce red highlighted overlay on top of element to remove.
// TODO: Wow, the design of the clickHide stuff is really dumb - gotta fix it sometime
currentElement = addElementOverlay(target);
// clickHide_mouseOver(lastRightClickEvent);
clickHide_mouseClick(lastRightClickEvent);
}
else
console.log("clickhide-new-filter: URLs don't match. Couldn't find that element.", msg.filter, url, lastRightClickEvent.target.src);
break;
case "clickhide-init":
if (clickHideFiltersDialog)
{
sendResponse({filters: clickHide_filters});
clickHideFiltersDialog.style.width = msg.width + "px";
clickHideFiltersDialog.style.height = msg.height + "px";
clickHideFiltersDialog.style.visibility = "visible";
}
break;
case "clickhide-move":
if (clickHideFiltersDialog)
{
clickHideFiltersDialog.style.left = (parseInt(clickHideFiltersDialog.style.left, 10) + msg.x) + "px";
clickHideFiltersDialog.style.top = (parseInt(clickHideFiltersDialog.style.top, 10) + msg.y) + "px";
}
break;
case "clickhide-close":
if (clickHideFiltersDialog && msg.remove)
{
// Explicitly get rid of currentElement
var element = currentElement.prisoner || currentElement;
if (element && element.parentNode)
element.parentNode.removeChild(element);
}
clickHide_deactivate();
break;
default:
sendResponse({});
break;
}
});
if (window == window.top)
ext.backgroundPage.sendMessage({type: "report-html-page"});
}