forked from adblockplus/adblockpluschrome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
431 lines (385 loc) · 12.9 KB
/
background.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
/*
* 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/>.
*/
with(require("filterClasses"))
{
this.Filter = Filter;
this.BlockingFilter = BlockingFilter;
this.WhitelistFilter = WhitelistFilter;
this.RegExpFilter = RegExpFilter;
}
with(require("subscriptionClasses"))
{
this.Subscription = Subscription;
this.DownloadableSubscription = DownloadableSubscription;
this.SpecialSubscription = SpecialSubscription;
}
with(require("whitelisting"))
{
this.checkWhitelisted = checkWhitelisted;
this.processKey = processKey;
this.getKey = getKey;
}
with(require("url"))
{
this.stringifyURL = stringifyURL;
this.isThirdParty = isThirdParty;
this.extractHostFromFrame = extractHostFromFrame;
}
var FilterStorage = require("filterStorage").FilterStorage;
var FilterNotifier = require("filterNotifier").FilterNotifier;
var ElemHide = require("elemHide").ElemHide;
var defaultMatcher = require("matcher").defaultMatcher;
var Prefs = require("prefs").Prefs;
var Synchronizer = require("synchronizer").Synchronizer;
var Utils = require("utils").Utils;
var parseFilters = require("filterValidation").parseFilters;
var composeFilters = require("filterComposer").composeFilters;
var updateIcon = require("icon").updateIcon;
var initNotifications = require("notificationHelper").initNotifications;
var showNextNotificationForUrl = require("notificationHelper").showNextNotificationForUrl;
var devtools = require("devtools");
var seenDataCorruption = false;
var filterlistsReinitialized = false;
function init()
{
var filtersLoaded = new Promise(function(resolve)
{
function onFilterAction(action)
{
if (action == "load")
{
FilterNotifier.removeListener(onFilterAction);
resolve();
}
}
FilterNotifier.addListener(onFilterAction);
});
function onLoaded()
{
var info = require("info");
var previousVersion = Prefs.currentVersion;
// There are no filters stored so we need to reinitialize all filterlists
if (!FilterStorage.firstRun && FilterStorage.subscriptions.length === 0)
{
filterlistsReinitialized = true;
previousVersion = null;
}
if (previousVersion != info.addonVersion || FilterStorage.firstRun)
{
seenDataCorruption = previousVersion && FilterStorage.firstRun;
Prefs.currentVersion = info.addonVersion;
addSubscription(previousVersion);
}
initNotifications();
// Update browser actions and context menus when whitelisting might have
// changed. That is now when initally loading the filters and later when
// importing backups or saving filter changes.
FilterNotifier.addListener(function(action)
{
if (action == "load" || action == "save")
refreshIconAndContextMenuForAllPages();
});
refreshIconAndContextMenuForAllPages();
}
Promise.all([filtersLoaded, Prefs.isLoaded]).then(onLoaded);
}
init();
// Special-case domains for which we cannot use style-based hiding rules.
// See http://crbug.com/68705.
var noStyleRulesHosts = ["mail.google.com", "mail.yahoo.com", "www.google.com"];
var htmlPages = new ext.PageMap();
var contextMenuItem = {
title: ext.i18n.getMessage("block_element"),
contexts: ["image", "video", "audio"],
onclick: function(page)
{
page.sendMessage({type: "clickhide-new-filter"});
}
};
// Adds or removes browser action icon according to options.
function refreshIconAndContextMenu(page)
{
var whitelisted = !!checkWhitelisted(page);
updateIcon(page, whitelisted);
// show or hide the context menu entry dependent on whether
// adblocking is active on that page
page.contextMenus.remove(contextMenuItem);
if (Prefs.shouldShowBlockElementMenu && !whitelisted && htmlPages.has(page))
page.contextMenus.create(contextMenuItem);
}
function refreshIconAndContextMenuForAllPages()
{
ext.pages.query({}, function(pages)
{
pages.forEach(refreshIconAndContextMenu);
});
}
/**
* This function is called on an extension update. It will add the default
* filter subscription if necessary.
*/
function addSubscription(prevVersion)
{
// Make sure to remove "Recommended filters", no longer necessary
var toRemove = "https://easylist-downloads.adblockplus.org/chrome_supplement.txt";
if (toRemove in FilterStorage.knownSubscriptions)
FilterStorage.removeSubscription(FilterStorage.knownSubscriptions[toRemove]);
// Add "acceptable ads" subscription for new users
var addAcceptable = !prevVersion;
if (addAcceptable)
{
addAcceptable = !FilterStorage.subscriptions.some(function(subscription)
{
return subscription.url == Prefs.subscriptions_exceptionsurl;
});
}
// Don't add subscription if the user has a subscription already
var addSubscription = !FilterStorage.subscriptions.some(function(subscription)
{
return subscription instanceof DownloadableSubscription &&
subscription.url != Prefs.subscriptions_exceptionsurl;
});
// If this isn't the first run, only add subscription if the user has no custom filters
if (addSubscription && prevVersion)
{
addSubscription = !FilterStorage.subscriptions.some(function(subscription)
{
return subscription.url != Prefs.subscriptions_exceptionsurl &&
subscription.filters.length;
});
}
// Add "acceptable ads" subscription
if (addAcceptable)
{
var subscription = Subscription.fromURL(Prefs.subscriptions_exceptionsurl);
if (subscription)
{
subscription.title = "Allow non-intrusive advertising";
FilterStorage.addSubscription(subscription);
if (subscription instanceof DownloadableSubscription && !subscription.lastDownload)
Synchronizer.execute(subscription);
}
else
addAcceptable = false;
}
// Add "anti-adblock messages" subscription for new users and users updating from old ABP versions
if (!prevVersion || Services.vc.compare(prevVersion, "1.8") < 0)
{
var subscription = Subscription.fromURL(Prefs.subscriptions_antiadblockurl);
if (subscription && !(subscription.url in FilterStorage.knownSubscriptions))
{
subscription.disabled = true;
FilterStorage.addSubscription(subscription);
if (subscription instanceof DownloadableSubscription && !subscription.lastDownload)
Synchronizer.execute(subscription);
}
}
if (!addSubscription && !addAcceptable)
return;
Promise.resolve(addSubscription && fetch("subscriptions.xml")
.then(function(response)
{
return response.text();
})
.then(function(text)
{
var doc = new DOMParser().parseFromString(text, "application/xml");
var nodes = doc.getElementsByTagName("subscription");
var node = Utils.chooseFilterSubscription(nodes);
var subscription = node && Subscription.fromURL(node.getAttribute("url"));
if (subscription)
{
FilterStorage.addSubscription(subscription);
subscription.disabled = false;
subscription.title = node.getAttribute("title");
subscription.homepage = node.getAttribute("homepage");
if (subscription instanceof DownloadableSubscription &&
!subscription.lastDownload)
Synchronizer.execute(subscription);
}
})
)
.then(function()
{
if (!Prefs.suppress_first_run_page)
ext.pages.open(ext.getURL("firstRun.html"));
});
}
Prefs.onChanged.addListener(function(name)
{
if (name == "shouldShowBlockElementMenu")
refreshIconAndContextMenuForAllPages();
});
// This is a hack to speedup loading of the options page on Safari.
// Once we replaced the background page proxy with message passing
// this global function should removed.
function getUserFilters()
{
var filters = [];
var exceptions = [];
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))
exceptions.push(RegExp.$1);
else
filters.push(filter.text);
}
}
return {filters: filters, exceptions: exceptions};
}
ext.onMessage.addListener(function (msg, sender, sendResponse)
{
switch (msg.type)
{
case "get-selectors":
var selectors = [];
var trace = devtools && devtools.hasPanel(sender.page);
if (!checkWhitelisted(sender.page, sender.frame,
RegExpFilter.typeMap.DOCUMENT |
RegExpFilter.typeMap.ELEMHIDE))
{
var noStyleRules = false;
var specificOnly = checkWhitelisted(sender.page, sender.frame,
RegExpFilter.typeMap.GENERICHIDE);
var host = extractHostFromFrame(sender.frame);
for (var i = 0; i < noStyleRulesHosts.length; i++)
{
var noStyleHost = noStyleRulesHosts[i];
if (host == noStyleHost || (host.length > noStyleHost.length &&
host.substr(host.length - noStyleHost.length - 1) == "." + noStyleHost))
{
noStyleRules = true;
}
}
selectors = ElemHide.getSelectorsForDomain(host, specificOnly);
if (noStyleRules)
{
selectors = selectors.filter(function(s)
{
return !/\[style[\^\$]?=/.test(s);
});
}
}
sendResponse({selectors: selectors, trace: trace});
break;
case "should-collapse":
if (checkWhitelisted(sender.page, sender.frame))
{
sendResponse(false);
break;
}
var typeMask = RegExpFilter.typeMap[msg.mediatype];
var documentHost = extractHostFromFrame(sender.frame);
var sitekey = getKey(sender.page, sender.frame);
var blocked = false;
var specificOnly = checkWhitelisted(
sender.page, sender.frame,
RegExpFilter.typeMap.GENERICBLOCK
);
for (var i = 0; i < msg.urls.length; i++)
{
var url = new URL(msg.urls[i], msg.baseURL);
var filter = defaultMatcher.matchesAny(
stringifyURL(url), typeMask,
documentHost, isThirdParty(url, documentHost),
sitekey, specificOnly
);
if (filter instanceof BlockingFilter)
{
if (filter.collapse != null)
{
sendResponse(filter.collapse);
return;
}
blocked = true;
}
}
sendResponse(blocked && Prefs.hidePlaceholders);
break;
case "get-domain-enabled-state":
// Returns whether this domain is in the exclusion list.
// The browser action popup asks us this.
if(sender.page)
{
sendResponse({enabled: !checkWhitelisted(sender.page)});
return;
}
break;
case "add-filters":
var result = parseFilters(msg.text);
if (result.errors.length > 0)
{
sendResponse({status: "invalid", error: result.errors.join("\n")});
break;
}
for (var i = 0; i < result.filters.length; i++)
FilterStorage.addFilter(result.filters[i]);
sendResponse({status: "ok"});
break;
case "add-sitekey":
processKey(msg.token, sender.page, sender.frame);
break;
case "report-html-page":
htmlPages.set(sender.page, null);
refreshIconAndContextMenu(sender.page);
break;
case "compose-filters":
sendResponse(composeFilters({
tagName: msg.tagName,
id: msg.id,
src: msg.src,
style: msg.style,
classes: msg.classes,
urls: msg.urls,
type: msg.mediatype,
baseURL: msg.baseURL,
page: sender.page,
frame: sender.frame
}));
break;
case "trace-elemhide":
devtools.logHiddenElements(
sender.page, msg.selectors,
extractHostFromFrame(sender.frame)
);
break;
case "forward":
if (sender.page)
{
if (msg.expectsResponse)
{
sender.page.sendMessage(msg.payload, sendResponse);
return true;
}
sender.page.sendMessage(msg.payload);
}
break;
}
});
// update icon when page changes location
ext.pages.onLoading.addListener(function(page)
{
page.sendMessage({type: "clickhide-deactivate"});
refreshIconAndContextMenu(page);
showNextNotificationForUrl(page.url);
});