forked from Sparticuz/chrome-aws-lambda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adblock.ts
48 lines (41 loc) · 1.22 KB
/
adblock.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
import { promises } from 'fs';
import { get } from 'https';
import { Page } from 'puppeteer-core';
let adblocker: any = null;
/**
* Enables ad blocking in page.
* Requires `@cliqz/adblocker-puppeteer` package.
*
* @param page - Page to hook to.
*/
export = async function (page: Page): Promise<Page> {
if (adblocker == null) {
const { fullLists, PuppeteerBlocker } = require('@cliqz/adblocker-puppeteer');
adblocker = await PuppeteerBlocker.fromLists(
(url: string) => {
return new Promise((resolve, reject) => {
return get(url, (response) => {
if (response.statusCode !== 200) {
return reject(`Unexpected status code: ${response.statusCode}.`);
}
let result = '';
response.on('data', (chunk) => {
result += chunk;
});
response.on('end', () => {
return resolve({ text: () => result });
});
});
});
},
fullLists,
{ enableCompression: false },
{
path: '/tmp/adblock.bin',
read: promises.readFile,
write: promises.writeFile,
}
);
}
return await adblocker.enableBlockingInPage(page).then(() => page);
}