Skip to content

Instantly share code, notes, and snippets.

@winstxnhdw
Last active April 25, 2023 09:06
Show Gist options
  • Save winstxnhdw/9363745a99c0de21508dfa597b8290aa to your computer and use it in GitHub Desktop.
Save winstxnhdw/9363745a99c0de21508dfa597b8290aa to your computer and use it in GitHub Desktop.
Helper script to retrieve endpoint(s) from a route with Playwright.
import type { Browser, BrowserContext, BrowserType, LaunchOptions, Page } from 'playwright'
import { chromium, firefox, webkit } from 'playwright'
type BrowserTypes = 'chromium' | 'webkit' | 'firefox'
type Endpoint = {
url: string
headers: Record<string, string>
}
export class PlaywrightBrowser {
private browser: Browser
context: BrowserContext
constructor(browser: Browser, browser_context: BrowserContext) {
this.browser = browser
this.context = browser_context
}
async shutdown() {
await this.context.close()
await this.browser.close()
}
}
export const get_browser = async (browser_type: BrowserTypes, launch_options: LaunchOptions) => {
const browser_types = new Map([
['chromium', chromium],
['webkit', webkit],
['firefox', firefox]
]) as Map<BrowserTypes, BrowserType>
const browser_object = browser_types.get(browser_type) as BrowserType
const browser_instance = await browser_object.launch(launch_options)
const browser_context = await browser_instance.newContext()
return new PlaywrightBrowser(browser_instance, browser_context)
}
export const launch_page_instance = async (browser: BrowserContext, middleware: (page: Page) => Promise<void>) => {
const page = await browser.newPage()
await middleware(page)
await page.close()
}
export const get_endpoint = async (page: Page, url: string, endpoint_pattern: string): Promise<Endpoint> =>
new Promise((resolve, reject) =>
page
.route(endpoint_pattern, async (route) => {
const request = route.request()
resolve({ url: request.url(), headers: request.headers() })
})
.then(() => page.goto(url).catch(reject))
.catch(reject)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment