export async function testPlaywright(): Promise<void> {
await usePlaywright(async ({ ctx, page }) => {
await blockRequests(page)
await page.goto(url, { waitUntil: 'networkidle' })
// ...
})
}
Last active
November 17, 2022 17:58
-
-
Save salazarr-js/feb5038f63bc230ac3b001431b9ecf33 to your computer and use it in GitHub Desktop.
Playwright lib hook
This file contains hidden or 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 { chromium, LaunchOptions } from 'playwright' | |
import type { Browser, BrowserContext, Page } from 'playwright' | |
/** */ | |
type UsePlaywrightCallback = (opt: { browser: Browser, ctx: BrowserContext, page: Page }) => Promise<void> | |
/** Expose a `playwright` browser, context and page to a callback that automatically close after finishing */ | |
export async function usePlaywright(cb: UsePlaywrightCallback): Promise<void> { | |
const devOpts: LaunchOptions = { headless: false, slowMo: 100, devtools: true } | |
const browser = await chromium.launch(process.env.DEV_MODE === 'true' ? devOpts : {}) | |
const ctx = await browser.newContext({ screen: { height: 1080, width: 1920 } }) | |
const page = await ctx.newPage() | |
await cb({ browser, ctx, page }) | |
await ctx.close() | |
await browser.close() | |
} | |
/** Block unnecessary resources and domains requests */ | |
async function blockRequests(page: Page): Promise<void> { | |
return await page.route('**/*', route => { | |
const resourcesToBlock = ['image', 'stylesheet', 'media', 'font','other', 'ping'] | |
const domainsToBlock = ['google-analytics.com', 'googletagmanager.com'] | |
const resourceType = route.request().resourceType() | |
if ( | |
resourcesToBlock.includes(resourceType) || | |
isBlacklisted(route.request().url(), domainsToBlock) | |
) | |
return route.abort() | |
return route.continue() | |
}) | |
} |
This file contains hidden or 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
/** Check if a url has a blacklisted domain */ | |
function isBlacklisted(url: string, domains: string[]) { | |
for (let i = 0; i < domains.length; i++) | |
if (url.includes(domains[i])) return true | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment