Ghostery adblocker Playwright wrapper
npm install @ghostery/adblocker-playwright
Efficient
· Minimal
· JavaScript
· TypeScript
· uBlock Origin- and Easylist-compatible
Node.js
· Puppeteer
· Electron
· WebExtension
---
Install: npm install --save @ghostery/adblocker-playwright.
For a complete example check-out: @ghostery/adblocker-playwright-example.
Creating an instance of PlaywrightBlocker and start blocking ads!
``javascript
import * as pw from 'playwright';
import { PlaywrightBlocker } from '@ghostery/adblocker-playwright';
import fetch from 'cross-fetch'; // required 'fetch'
const browser = await pw.firefox.launch({ headless: false });
const page = await browser.newPage();
PlaywrightBlocker.fromPrebuiltAdsAndTracking(fetch).then((blocker) => {
blocker.enableBlockingInPage(page);
});
`
You are ready to block ads!
There are other ways you can create an instance of the blocking engine to
start blocking ads.
If you already have filters locally:
`javascript
import { PlaywrightBlocker } from '@ghostery/adblocker-playwright';
const blocker = PlaywrightBlocker.parse(fs.readFileSync('easylist.txt', 'utf-8'));
`
Fetching lists from URLs:
`javascript
import { PlaywrightBlocker } from '@ghostery/adblocker-playwright';
import fetch from 'cross-fetch'; // required 'fetch'
const blocker = await PlaywrightBlocker.fromLists(fetch, [
'https://easylist.to/easylist/easylist.txt'
]);
`
Use ready-made configs to block ads and optionally trackers:
`javascript
import { PlaywrightBlocker } from '@ghostery/adblocker-playwright';
import fetch from 'cross-fetch'; // required 'fetch'
let blocker = await PlaywrightBlocker.fromPrebuiltAdsOnly(fetch); // ads only
blocker = await PlaywrightBlocker.fromPrebuiltAdsAndTracking(fetch); // ads and tracking
`
To stop blocking ads in a page:
`javascript`
await blocker.disableBlockingInPage(page);
To avoid having to create the same instance of PlaywrightBlocker all over again,
you can serialize it to a byte-array which you can store on disk for faster
loading.
`javascript
import * as pw from 'playwright';
import { PlaywrightBlocker } from '@ghostery/adblocker-playwright';
import fetch from 'cross-fetch'; // required 'fetch'
import { promises as fs } from 'fs'; // used for caching
const browser = await pw.firefox.launch({ headless: false });
const page = await browser.newPage();
PlaywrightBlocker.fromPrebuiltAdsAndTracking(fetch, {
path: 'engine.bin',
read: fs.readFile,
write: fs.writeFile,
}).then((blocker) => {
blocker.enableBlockingInPage(page);
});
`
Or you can do this manually to control the way caching is done:
`javascript
import { PlaywrightBlocker } from '@ghostery/adblocker-playwright';
import fetch from 'cross-fetch'; // required 'fetch'
PlaywrightBlocker.fromPrebuiltAdsAndTracking(fetch).then((blocker) => {
const buffer = blocker.serialize();
const restoredBlocker = PlaywrightBlocker.deserialize(buffer);
// restoredBlocker is deep-equal to blocker!``
});