-
Notifications
You must be signed in to change notification settings - Fork 91
/
background.ts
92 lines (76 loc) · 2.67 KB
/
background.ts
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
/*!
* Copyright (c) 2017-present Cliqz GmbH. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { browser } from 'webextension-polyfill-ts';
import {
BlockingResponse,
fullLists,
HTMLSelector,
Request,
WebExtensionBlocker,
} from '@cliqz/adblocker-webextension';
/**
* Keep track of number of network requests altered for each tab
*/
const counter: Map<number, number> = new Map();
/**
* Helper function used to both reset, increment and show the current value of
* the blocked requests counter for a given tabId.
*/
function updateBlockedCounter(tabId: number, { reset = false, incr = false } = {}) {
counter.set(tabId, (reset === true ? 0 : counter.get(tabId) || 0) + (incr === true ? 1 : 0));
chrome.browserAction.setBadgeText({
text: '' + (counter.get(tabId) || 0),
});
}
function incrementBlockedCounter(request: Request, blockingResponse: BlockingResponse): void {
updateBlockedCounter(request.tabId, {
incr: Boolean(blockingResponse.match),
reset: request.isMainFrame(),
});
}
// Whenever the active tab changes, then we update the count of blocked request
chrome.tabs.onActivated.addListener(({ tabId }: chrome.tabs.TabActiveInfo) =>
updateBlockedCounter(tabId),
);
// Reset counter if tab is reloaded
chrome.tabs.onUpdated.addListener((tabId, { status, url }) => {
if (status === 'loading' && url === undefined) {
updateBlockedCounter(tabId, {
incr: false,
reset: true,
});
}
});
WebExtensionBlocker.fromLists(fetch, fullLists, {
enableCompression: true,
enableHtmlFiltering: true,
loadExtendedSelectors: true,
}).then((blocker: WebExtensionBlocker) => {
blocker.enableBlockingInBrowser(browser);
blocker.on('request-blocked', (request: Request, result: BlockingResponse) => {
incrementBlockedCounter(request, result);
console.log('block', request.url);
});
blocker.on('request-redirected', (request: Request, result: BlockingResponse) => {
incrementBlockedCounter(request, result);
console.log('redirect', request.url, result);
});
blocker.on('csp-injected', (request: Request) => {
console.log('csp', request.url);
});
blocker.on('script-injected', (script: string, url: string) => {
console.log('script', script.length, url);
});
blocker.on('style-injected', (style: string, url: string) => {
console.log('style', url, style.length);
});
blocker.on('html-filtered', (htmlSelectors: HTMLSelector[]) => {
console.log('html selectors', htmlSelectors);
});
console.log('Ready to roll!');
});