Last active
June 2, 2022 17:43
-
-
Save clouedoc/02c7214f62a431de72ce51516964d047 to your computer and use it in GitHub Desktop.
This puppeteer-extra plugin blocks requests based on patterns. It includes supports for service workers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { CDPSession, Page, Target, WebWorker } from 'puppeteer'; | |
import { PuppeteerExtraPlugin } from 'puppeteer-extra-plugin'; | |
const blockedResources: string[] = [ | |
// Assets | |
'*/favicon.ico', | |
'.css', | |
'.jpg', | |
'.jpeg', | |
'.png', | |
'.svg', | |
'.woff', | |
'.otf', | |
// Analytics and other fluff | |
'*.optimizely.com', | |
'everesttech.net', | |
'userzoom.com', | |
'doubleclick.net', | |
'googleadservices.com', | |
'adservice.google.com/*', | |
'connect.facebook.com', | |
'connect.facebook.net', | |
'sp.analytics.yahoo.com', | |
]; | |
export class BlockAssetsPlugin extends PuppeteerExtraPlugin { | |
public get name(): string { | |
return 'block-assets-plugin'; | |
} | |
protected async blockUrlList(session: CDPSession): Promise<void> { | |
await session.send('Network.enable'); | |
await session.send('Network.setBlockedURLs', { | |
urls: blockedResources, | |
}); | |
} | |
public async onTargetCreated(target: Target): Promise<void> { | |
if (target.type() === 'service_worker') { | |
const worker: WebWorker | null = await target.worker(); | |
const session: CDPSession = await worker!._client; | |
await this.blockUrlList(session); | |
this.debug('Blocked requests on service worker'); | |
} | |
} | |
public async onPageCreated(page: Page): Promise<void> { | |
// @ts-expect-error | |
const session: CDPSession = await page._client; | |
await this.blockUrlList(session); | |
this.debug('Blocked requests on page'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment