playwright#Route TypeScript Examples

The following examples show how to use playwright#Route. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: with-mocks.ts    From playwright-fluent with MIT License 6 votes vote down vote up
async function fullfillRouteWithMock(
  mock: FluentMock,
  route: Route,
  options: Partial<RouteOptions>,
): Promise<void> {
  if (mock.delayInMilliseconds > 0) {
    setTimeout(() => route.fulfill(options), mock.delayInMilliseconds);
    return;
  }

  route.fulfill(options);
}
Example #2
Source File: functions.ts    From actor-facebook-scraper with Apache License 2.0 4 votes vote down vote up
resourceCache = (paths: RegExp[]) => {
    // Cache resources to ease the data transfer
    const cache = new Map<string, {
        loaded: boolean,
        contentType?: string,
        content?: Buffer,
        headers?: any
    }>();

    return async (page: Page) => {
        const response = async (res: HTTPResponse) => {
            try {
                if (page.isClosed()) {
                    await cleanup();
                    return;
                }

                if (['script', 'stylesheet'].includes(res.request().resourceType())) {
                    const url = res.url();
                    const content = cache.get(url);

                    if (content && !content.loaded) {
                        const buffer = await res.body();

                        /* eslint-disable */
                        const {
                            date,
                            expires,
                            'last-modified': lastModified,
                            'content-length': contentLength,
                            ...headers
                        } = res.headers();
                        /* eslint-enable */

                        cache.set(url, {
                            contentType: res.headers()['content-type'],
                            loaded: buffer.length > 0,
                            content: buffer,
                            headers,
                        });
                    }
                }
            } catch (e) {
                await cleanup();
                log.debug('Cache error', { e: e.message });
            }
        };

        const request = async (route: Route) => {
            if (page.isClosed()) {
                await cleanup();
                return;
            }

            const req = route.request();

            const url = req.url();

            try {
                if ([
                    '.woff',
                    '.webp',
                    '.mov',
                    '.mpeg',
                    '.mpg',
                    '.mp4',
                    '.woff2',
                    '.ttf',
                    '.ico',
                    'static_map.php',
                    'ajax/bz',
                ].some((resource) => url.includes(resource))) {
                    await route.abort();
                    return;
                }

                if (req.resourceType() === 'image') {
                    // serve empty images so the `onload` events don't fail
                    if (url.includes('.jpg') || url.includes('.jpeg')) {
                        return await route.fulfill(images.jpg);
                    }

                    if (url.includes('.png')) {
                        return await route.fulfill(images.png);
                    }

                    if (url.includes('.gif')) {
                        return await route.fulfill(images.gif);
                    }
                } else if (['script', 'stylesheet'].includes(req.resourceType()) && paths.some((path) => path.test(url))) {
                    const content = cache.get(url);

                    // log.debug('Cache', { url, headers: content?.headers, type: content?.contentType, length: content?.content?.length });

                    if (content?.loaded === true) {
                        return await route.fulfill({
                            body: content.content,
                            status: 200,
                            contentType: content.contentType,
                            headers: content.headers,
                        });
                    }

                    cache.set(url, {
                        loaded: false,
                    });
                } else if (req.resourceType() === 'media') {
                    await route.abort();
                    return;
                }

                await route.continue();
            } catch (e) {
                await cleanup();
                log.debug('Resource cache', { e: e.message });
            }
        };

        const cleanup = async () => {
            try {
                await page.unroute('**/*');
                page.off('response', response);
            } catch (e) {
                log.debug('Cache', { error: e.message });
            }
        };

        await page.route('**/*', request);
        page.on('response', response);
    };
}