forked from adblockplus/adblockpluschrome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
options.js
708 lines (620 loc) · 20.8 KB
/
options.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
/*
* This file is part of Adblock Plus <https://adblockplus.org/>,
* Copyright (C) 2006-2016 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/>.
*/
var backgroundPage = ext.backgroundPage.getWindow();
var require = backgroundPage.require;
with(require("filterClasses"))
{
this.Filter = Filter;
this.WhitelistFilter = WhitelistFilter;
}
with(require("subscriptionClasses"))
{
this.Subscription = Subscription;
this.SpecialSubscription = SpecialSubscription;
this.DownloadableSubscription = DownloadableSubscription;
}
with(require("filterValidation"))
{
this.parseFilter = parseFilter;
this.parseFilters = parseFilters;
}
var FilterStorage = require("filterStorage").FilterStorage;
var FilterNotifier = require("filterNotifier").FilterNotifier;
var Prefs = require("prefs").Prefs;
var Synchronizer = require("synchronizer").Synchronizer;
var Utils = require("utils").Utils;
var NotificationStorage = require("notification").Notification;
// Loads options from localStorage and sets UI elements accordingly
function loadOptions()
{
// Set page title to i18n version of "Adblock Plus Options"
document.title = i18n.getMessage("options");
// Set links
$("#acceptableAdsLink").attr("href", Prefs.subscriptions_exceptionsurl);
$("#acceptableAdsDocs").attr("href", Utils.getDocLink("acceptable_ads"));
setLinks("filter-must-follow-syntax", Utils.getDocLink("filterdoc"));
setLinks("found-a-bug", Utils.getDocLink(require("info").application + "_support"));
// Add event listeners
window.addEventListener("unload", unloadOptions, false);
$("#updateFilterLists").click(updateFilterLists);
$("#startSubscriptionSelection").click(startSubscriptionSelection);
$("#subscriptionSelector").change(updateSubscriptionSelection);
$("#addSubscription").click(addSubscription);
$("#acceptableAds").click(allowAcceptableAds);
$("#whitelistForm").submit(addWhitelistDomain);
$("#removeWhitelist").click(removeSelectedExcludedDomain);
$("#customFilterForm").submit(addTypedFilter);
$("#removeCustomFilter").click(removeSelectedFilters);
$("#rawFiltersButton").click(toggleFiltersInRawFormat);
$("#importRawFilters").click(importRawFiltersText);
FilterNotifier.addListener(onFilterChange);
// Display jQuery UI elements
$("#tabs").tabs();
$("button").button();
$(".refreshButton").button("option", "icons", {primary: "ui-icon-refresh"});
$(".addButton").button("option", "icons", {primary: "ui-icon-plus"});
$(".removeButton").button("option", "icons", {primary: "ui-icon-minus"});
// Popuplate option checkboxes
initCheckbox("shouldShowBlockElementMenu");
if (Prefs.notifications_showui)
{
initCheckbox("shouldShowNotifications", {
get: function()
{
return Prefs.notifications_ignoredcategories.indexOf("*") == -1;
},
toggle: function()
{
NotificationStorage.toggleIgnoreCategory("*");
return this.get();
}
});
}
else
document.getElementById("shouldShowNotificationsContainer").hidden = true;
ext.onMessage.addListener(onMessage);
ext.backgroundPage.sendMessage({
type: "app.listen",
filter: ["addSubscription"]
});
// Load recommended subscriptions
loadRecommendations();
// Show user's filters
reloadFilters();
}
$(loadOptions);
function onMessage(msg)
{
if (msg.type == "app.listen")
{
if (msg.action == "addSubscription")
{
var subscription = msg.args[0];
startSubscriptionSelection(subscription.title, subscription.url);
}
}
else if (msg.type == "focus-section")
{
var tabs = document.getElementsByClassName("ui-tabs-panel");
for (var i = 0; i < tabs.length; i++)
{
var found = tabs[i].querySelector("[data-section='" + msg.section + "']");
if (!found)
continue;
var previous = document.getElementsByClassName("focused");
if (previous.length > 0)
previous[0].classList.remove("focused");
var tab = $("[href='#" + tabs[i].id + "']");
$("#tabs").tabs("select", tab.parent().index());
found.classList.add("focused");
}
}
};
// Reloads the displayed subscriptions and filters
function reloadFilters()
{
// Load user filter URLs
var container = document.getElementById("filterLists");
while (container.lastChild)
container.removeChild(container.lastChild);
var hasAcceptable = false;
for (var i = 0; i < FilterStorage.subscriptions.length; i++)
{
var subscription = FilterStorage.subscriptions[i];
if (subscription instanceof SpecialSubscription)
continue;
if (subscription.url == Prefs.subscriptions_exceptionsurl)
{
hasAcceptable = true;
continue;
}
addSubscriptionEntry(subscription);
}
$("#acceptableAds").prop("checked", hasAcceptable);
// User-entered filters
var userFilters = backgroundPage.getUserFilters();
populateList("userFiltersBox", userFilters.filters);
populateList("excludedDomainsBox", userFilters.exceptions);
}
// Cleans up when the options window is closed
function unloadOptions()
{
FilterNotifier.removeListener(onFilterChange);
}
function initCheckbox(id, descriptor)
{
var checkbox = document.getElementById(id);
if (descriptor && descriptor.get)
checkbox.checked = descriptor.get();
else
checkbox.checked = Prefs[id];
checkbox.addEventListener("click", function()
{
if (descriptor && descriptor.toggle)
checkbox.checked = descriptor.toggle();
Prefs[id] = checkbox.checked;
}, false);
}
var delayedSubscriptionSelection = null;
function loadRecommendations()
{
fetch("subscriptions.xml")
.then(function(response)
{
return response.text();
})
.then(function(text)
{
var selectedIndex = 0;
var selectedPrefix = null;
var matchCount = 0;
var list = document.getElementById("subscriptionSelector");
var doc = new DOMParser().parseFromString(text, "application/xml");
var elements = doc.documentElement.getElementsByTagName("subscription");
for (var i = 0; i < elements.length; i++)
{
var element = elements[i];
var option = new Option();
option.text = element.getAttribute("title") + " (" +
element.getAttribute("specialization") + ")";
option._data = {
title: element.getAttribute("title"),
url: element.getAttribute("url"),
homepage: element.getAttribute("homepage")
};
var prefixes = element.getAttribute("prefixes");
var prefix = Utils.checkLocalePrefixMatch(prefixes);
if (prefix)
{
option.style.fontWeight = "bold";
option.style.backgroundColor = "#E0FFE0";
option.style.color = "#000000";
if (!selectedPrefix || selectedPrefix.length < prefix.length)
{
selectedIndex = i;
selectedPrefix = prefix;
matchCount = 1;
}
else if (selectedPrefix && selectedPrefix.length == prefix.length)
{
matchCount++;
// If multiple items have a matching prefix of the same length:
// Select one of the items randomly, probability should be the same
// for all items. So we replace the previous match here with
// probability 1/N (N being the number of matches).
if (Math.random() * matchCount < 1)
{
selectedIndex = i;
selectedPrefix = prefix;
}
}
}
list.appendChild(option);
}
var option = new Option();
var label = i18n.getMessage("filters_addSubscriptionOther_label");
option.text = label + "\u2026";
option._data = null;
list.appendChild(option);
list.selectedIndex = selectedIndex;
if (delayedSubscriptionSelection)
startSubscriptionSelection.apply(null, delayedSubscriptionSelection);
});
}
function startSubscriptionSelection(title, url)
{
var list = document.getElementById("subscriptionSelector");
if (list.length == 0)
{
delayedSubscriptionSelection = [title, url];
return;
}
$("#tabs").tabs("select", 0);
$("#addSubscriptionContainer").show();
$("#addSubscriptionButton").hide();
$("#subscriptionSelector").focus();
if (typeof url != "undefined")
{
list.selectedIndex = list.length - 1;
document.getElementById("customSubscriptionTitle").value = title;
document.getElementById("customSubscriptionLocation").value = url;
}
updateSubscriptionSelection();
document.getElementById("addSubscriptionContainer").scrollIntoView(true);
}
function updateSubscriptionSelection()
{
var list = document.getElementById("subscriptionSelector");
var data = list.options[list.selectedIndex]._data;
if (data)
$("#customSubscriptionContainer").hide();
else
{
$("#customSubscriptionContainer").show();
$("#customSubscriptionTitle").focus();
}
}
function addSubscription()
{
var list = document.getElementById("subscriptionSelector");
var data = list.options[list.selectedIndex]._data;
if (data)
doAddSubscription(data.url, data.title, data.homepage);
else
{
var url = document.getElementById("customSubscriptionLocation").value.trim();
if (!/^https?:/i.test(url))
{
alert(i18n.getMessage("global_subscription_invalid_location"));
$("#customSubscriptionLocation").focus();
return;
}
var title = document.getElementById("customSubscriptionTitle").value.trim();
if (!title)
title = url;
doAddSubscription(url, title, null);
}
$("#addSubscriptionContainer").hide();
$("#customSubscriptionContainer").hide();
$("#addSubscriptionButton").show();
}
function doAddSubscription(url, title, homepage)
{
if (url in FilterStorage.knownSubscriptions)
return;
var subscription = Subscription.fromURL(url);
if (!subscription)
return;
subscription.title = title;
if (homepage)
subscription.homepage = homepage;
FilterStorage.addSubscription(subscription);
if (subscription instanceof DownloadableSubscription && !subscription.lastDownload)
Synchronizer.execute(subscription);
}
function allowAcceptableAds(event)
{
var subscription = Subscription.fromURL(Prefs.subscriptions_exceptionsurl);
if (!subscription)
return;
subscription.disabled = false;
subscription.title = "Allow non-intrusive advertising";
if ($("#acceptableAds").prop("checked"))
{
FilterStorage.addSubscription(subscription);
if (subscription instanceof DownloadableSubscription && !subscription.lastDownload)
Synchronizer.execute(subscription);
}
else
FilterStorage.removeSubscription(subscription);
}
function findSubscriptionElement(subscription)
{
var children = document.getElementById("filterLists").childNodes;
for (var i = 0; i < children.length; i++)
if (children[i]._subscription == subscription)
return children[i];
return null;
}
function updateSubscriptionInfo(element)
{
var subscription = element._subscription;
var title = element.getElementsByClassName("subscriptionTitle")[0];
title.textContent = subscription.title;
title.setAttribute("title", subscription.url);
if (subscription.homepage)
title.href = subscription.homepage;
else
title.href = subscription.url;
var enabled = element.getElementsByClassName("subscriptionEnabled")[0];
enabled.checked = !subscription.disabled;
var lastUpdate = element.getElementsByClassName("subscriptionUpdate")[0];
lastUpdate.classList.remove("error");
if (Synchronizer.isExecuting(subscription.url))
lastUpdate.textContent = i18n.getMessage("filters_subscription_lastDownload_inProgress");
else if (subscription.downloadStatus && subscription.downloadStatus != "synchronize_ok")
{
var map =
{
"synchronize_invalid_url": "filters_subscription_lastDownload_invalidURL",
"synchronize_connection_error": "filters_subscription_lastDownload_connectionError",
"synchronize_invalid_data": "filters_subscription_lastDownload_invalidData",
"synchronize_checksum_mismatch": "filters_subscription_lastDownload_checksumMismatch"
};
if (subscription.downloadStatus in map)
lastUpdate.textContent = i18n.getMessage(map[subscription.downloadStatus]);
else
lastUpdate.textContent = subscription.downloadStatus;
lastUpdate.classList.add("error");
}
else if (subscription.lastDownload > 0)
{
var timeDate = i18n_timeDateStrings(subscription.lastDownload * 1000);
var messageID = (timeDate[1] ? "last_updated_at" : "last_updated_at_today");
lastUpdate.textContent = i18n.getMessage(messageID, timeDate);
}
}
function onFilterChange(action, item, param1, param2)
{
switch (action)
{
case "load":
reloadFilters();
break;
case "subscription.title":
case "subscription.disabled":
case "subscription.homepage":
case "subscription.lastDownload":
case "subscription.downloadStatus":
var element = findSubscriptionElement(item);
if (element)
updateSubscriptionInfo(element);
break;
case "subscription.added":
if (item instanceof SpecialSubscription)
{
for (var i = 0; i < item.filters.length; i++)
onFilterChange("filter.added", item.filters[i]);
}
else if (item.url == Prefs.subscriptions_exceptionsurl)
$("#acceptableAds").prop("checked", true);
else if (!findSubscriptionElement(item))
addSubscriptionEntry(item);
break;
case "subscription.removed":
if (item instanceof SpecialSubscription)
{
for (var i = 0; i < item.filters.length; i++)
onFilterChange("filter.removed", item.filters[i]);
}
else if (item.url == Prefs.subscriptions_exceptionsurl)
$("#acceptableAds").prop("checked", false);
else
{
var element = findSubscriptionElement(item);
if (element)
element.parentNode.removeChild(element);
}
break;
case "filter.added":
if (item instanceof WhitelistFilter && /^@@\|\|([^\/:]+)\^\$document$/.test(item.text))
appendToListBox("excludedDomainsBox", RegExp.$1);
else
appendToListBox("userFiltersBox", item.text);
break;
case "filter.removed":
if (item instanceof WhitelistFilter && /^@@\|\|([^\/:]+)\^\$document$/.test(item.text))
removeFromListBox("excludedDomainsBox", RegExp.$1);
else
removeFromListBox("userFiltersBox", item.text);
break;
}
}
// Populates a list box with a number of entries
function populateList(id, entries)
{
var list = document.getElementById(id);
while (list.lastChild)
list.removeChild(list.lastChild);
entries.sort();
for (var i = 0; i < entries.length; i++)
{
var option = new Option();
option.text = entries[i];
option.value = entries[i];
list.appendChild(option);
}
}
// Add a filter string to the list box.
function appendToListBox(boxId, text)
{
var elt = new Option(); /* Note: document.createElement("option") is unreliable in Opera */
elt.text = text;
elt.value = text;
document.getElementById(boxId).appendChild(elt);
}
// Remove a filter string from a list box.
function removeFromListBox(boxId, text)
{
var list = document.getElementById(boxId);
for (var i = 0; i < list.length; i++)
if (list.options[i].value == text)
list.remove(i--);
}
function addWhitelistDomain(event)
{
event.preventDefault();
var domain = document.getElementById("newWhitelistDomain").value.replace(/\s/g, "");
document.getElementById("newWhitelistDomain").value = "";
if (!domain)
return;
var filterText = "@@||" + domain + "^$document";
FilterStorage.addFilter(Filter.fromText(filterText));
}
// Adds filter text that user typed to the selection box
function addTypedFilter(event)
{
event.preventDefault();
var element = document.getElementById("newFilter");
var result = parseFilter(element.value);
if (result.error)
{
alert(result.error);
return;
}
if (result.filter)
FilterStorage.addFilter(result.filter);
element.value = "";
}
// Removes currently selected whitelisted domains
function removeSelectedExcludedDomain(event)
{
event.preventDefault();
var excludedDomainsBox = document.getElementById("excludedDomainsBox");
var remove = [];
for (var i = 0; i < excludedDomainsBox.length; i++)
if (excludedDomainsBox.options[i].selected)
remove.push(excludedDomainsBox.options[i].value);
if (!remove.length)
return;
for (var i = 0; i < remove.length; i++)
FilterStorage.removeFilter(Filter.fromText("@@||" + remove[i] + "^$document"));
}
// Removes all currently selected filters
function removeSelectedFilters(event)
{
event.preventDefault();
var userFiltersBox = document.getElementById("userFiltersBox");
var remove = [];
for (var i = 0; i < userFiltersBox.length; i++)
if (userFiltersBox.options[i].selected)
remove.push(userFiltersBox.options[i].value);
if (!remove.length)
return;
for (var i = 0; i < remove.length; i++)
FilterStorage.removeFilter(Filter.fromText(remove[i]));
}
// Shows raw filters box and fills it with the current user filters
function toggleFiltersInRawFormat(event)
{
event.preventDefault();
$("#rawFilters").toggle();
if ($("#rawFilters").is(":visible"))
{
var userFiltersBox = document.getElementById("userFiltersBox");
var text = "";
for (var i = 0; i < userFiltersBox.length; i++)
text += userFiltersBox.options[i].value + "\n";
document.getElementById("rawFiltersText").value = text;
}
}
// Imports filters in the raw text box
function importRawFiltersText()
{
var text = document.getElementById("rawFiltersText").value;
var result = parseFilters(text);
var errors = result.errors.filter(function(e)
{
return e.type != "unexpected-filter-list-header";
});
if (errors.length > 0)
{
alert(errors.join("\n"));
return;
}
var seenFilter = Object.create(null);
for (var i = 0; i < result.filters.length; i++)
{
var filter = result.filters[i];
FilterStorage.addFilter(filter);
seenFilter[filter.text] = null;
}
var remove = [];
for (var i = 0; i < FilterStorage.subscriptions.length; i++)
{
var subscription = FilterStorage.subscriptions[i];
if (!(subscription instanceof SpecialSubscription))
continue;
for (var j = 0; j < subscription.filters.length; j++)
{
var filter = subscription.filters[j];
if (filter instanceof WhitelistFilter && /^@@\|\|([^\/:]+)\^\$document$/.test(filter.text))
continue;
if (!(filter.text in seenFilter))
remove.push(filter);
}
}
for (var i = 0; i < remove.length; i++)
FilterStorage.removeFilter(remove[i]);
$("#rawFilters").hide();
}
// Called when user explicitly requests filter list updates
function updateFilterLists()
{
for (var i = 0; i < FilterStorage.subscriptions.length; i++)
{
var subscription = FilterStorage.subscriptions[i];
if (subscription instanceof DownloadableSubscription)
Synchronizer.execute(subscription, true, true);
}
}
// Adds a subscription entry to the UI.
function addSubscriptionEntry(subscription)
{
var template = document.getElementById("subscriptionTemplate");
var element = template.cloneNode(true);
element.removeAttribute("id");
element._subscription = subscription;
var removeButton = element.getElementsByClassName("subscriptionRemoveButton")[0];
removeButton.setAttribute("title", removeButton.textContent);
removeButton.textContent = "\xD7";
removeButton.addEventListener("click", function()
{
if (!confirm(i18n.getMessage("global_remove_subscription_warning")))
return;
FilterStorage.removeSubscription(subscription);
}, false);
var enabled = element.getElementsByClassName("subscriptionEnabled")[0];
enabled.addEventListener("click", function()
{
if (subscription.disabled == !enabled.checked)
return;
subscription.disabled = !enabled.checked;
}, false);
updateSubscriptionInfo(element);
document.getElementById("filterLists").appendChild(element);
}
function setLinks(id)
{
var element = document.getElementById(id);
if (!element)
return;
var links = element.getElementsByTagName("a");
for (var i = 0; i < links.length; i++)
{
if (typeof arguments[i + 1] == "string")
{
links[i].href = arguments[i + 1];
links[i].setAttribute("target", "_blank");
}
else if (typeof arguments[i + 1] == "function")
{
links[i].href = "javascript:void(0);";
links[i].addEventListener("click", arguments[i + 1], false);
}
}
}