Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/src/api/class-browsercontext.md
Original file line number Diff line number Diff line change
Expand Up @@ -1262,6 +1262,32 @@ handler function to route the request.

How often a route should be used. By default it will be used every time.

## async method: BrowserContext.routeFromCache
* since: v1.62
* langs: js
- returns: <[Disposable]>

Caches responses for matching network requests on disk and replays them on subsequent runs.

On the first run every matching request goes to the network and its response (status, headers and body) is stored under [`option: BrowserContext.routeFromCache.dir`]. On later runs matching requests are served from disk without hitting the network. Non-matching requests are left untouched.

Responses are stored compactly: small bodies are inlined into a single append-only index, while large bodies are content-addressed and de-duplicated in a `blobs/` sub-directory. Only successful (`2xx`) responses are cached; other responses always go to the network.

**Usage**

```js
// Record on the first run, replay from disk afterwards.
await context.routeFromCache({ dir: '.cache' });
const page = await context.newPage();
await page.goto('https://github.com/microsoft/playwright/issues');
```

### param: BrowserContext.routeFromCache.options
* since: v1.62
- `options` <[Object]>
- `dir` <[string]> Directory used to store and read cached responses.
- `match` ?<[string]|[RegExp]|[URLPattern]> A glob pattern, regex or [URLPattern] that selects which request URLs are cached. When omitted, all `GET` requests are cached. Only `GET` requests are ever cached.

## async method: BrowserContext.routeFromHAR
* since: v1.23

Expand Down
30 changes: 30 additions & 0 deletions docs/src/api/class-page.md
Original file line number Diff line number Diff line change
Expand Up @@ -3822,6 +3822,36 @@ handler function to route the request.

How often a route should be used. By default it will be used every time.

## async method: Page.routeFromCache
* since: v1.62
* langs: js
- returns: <[Disposable]>

Caches responses for matching network requests on disk and replays them on subsequent runs.

On the first run every matching request goes to the network and its response (status, headers and body) is stored under [`option: Page.routeFromCache.dir`]. On later runs matching requests are served from disk without hitting the network. Non-matching requests are left untouched.

Responses are stored compactly: small bodies are inlined into a single append-only index, while large bodies are content-addressed and de-duplicated in a `blobs/` sub-directory. Only successful (`2xx`) responses are cached; other responses always go to the network.

**Usage**

```js
// Record on the first run, replay from disk afterwards.
await page.routeFromCache({ dir: '.cache' });
await page.goto('https://github.com/microsoft/playwright/issues');
```

```js
// Cache only requests under a specific path.
await page.routeFromCache({ dir: '.cache', match: '**/api/**' });
```

### param: Page.routeFromCache.options
* since: v1.62
- `options` <[Object]>
- `dir` <[string]> Directory used to store and read cached responses.
- `match` ?<[string]|[RegExp]|[URLPattern]> A glob pattern, regex or [URLPattern] that selects which request URLs are cached. When omitted, all `GET` requests are cached. Only `GET` requests are ever cached.

## async method: Page.routeFromHAR
* since: v1.23

Expand Down
4 changes: 4 additions & 0 deletions packages/isomorphic/protocolMetainfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ export const methodMetainfo = new Map<string, MethodMetainfo>([
['BrowserContext.setGeolocation', { title: 'Set geolocation', group: 'configuration', }],
['BrowserContext.setHTTPCredentials', { title: 'Set HTTP credentials', group: 'configuration', }],
['BrowserContext.setNetworkInterceptionPatterns', { title: 'Route requests', group: 'route', }],
['BrowserContext.routeFromCache', { title: 'Route from cache', group: 'route', }],
['BrowserContext.unrouteFromCache', { title: 'Stop routing from cache', group: 'route', }],
['BrowserContext.routeAPIRequestsFromHar', { internal: true, }],
['BrowserContext.unrouteAPIRequestsFromHar', { internal: true, }],
['BrowserContext.setWebSocketInterceptionPatterns', { title: 'Route WebSockets', group: 'route', }],
Expand Down Expand Up @@ -266,6 +268,8 @@ export const methodMetainfo = new Map<string, MethodMetainfo>([
['Page.screenshot', { title: 'Screenshot', snapshot: true, pause: true, }],
['Page.setExtraHTTPHeaders', { title: 'Set extra HTTP headers', group: 'configuration', }],
['Page.setNetworkInterceptionPatterns', { title: 'Route requests', group: 'route', }],
['Page.routeFromCache', { title: 'Route from cache', group: 'route', }],
['Page.unrouteFromCache', { title: 'Stop routing from cache', group: 'route', }],
['Page.setWebSocketInterceptionPatterns', { title: 'Route WebSockets', group: 'route', }],
['Page.setViewportSize', { title: 'Set viewport size', snapshot: true, pause: true, }],
['Page.keyboardDown', { title: 'Key down "{key}"', slowMo: true, snapshot: true, pause: true, input: true, }],
Expand Down
75 changes: 75 additions & 0 deletions packages/playwright-client/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4365,6 +4365,45 @@ export interface Page {
times?: number;
}): Promise<Disposable>;

/**
* Caches responses for matching network requests on disk and replays them on subsequent runs.
*
* On the first run every matching request goes to the network and its response (status, headers and body) is stored
* under [`dir`](https://playwright.dev/docs/api/class-page#page-route-from-cache-option-dir). On later runs matching
* requests are served from disk without hitting the network. Non-matching requests are left untouched.
*
* Responses are stored compactly: small bodies are inlined into a single append-only index, while large bodies are
* content-addressed and de-duplicated in a `blobs/` sub-directory. Only successful (`2xx`) responses are cached;
* other responses always go to the network.
*
* **Usage**
*
* ```js
* // Record on the first run, replay from disk afterwards.
* await page.routeFromCache({ dir: '.cache' });
* await page.goto('https://github.com/microsoft/playwright/issues');
* ```
*
* ```js
* // Cache only requests under a specific path.
* await page.routeFromCache({ dir: '.cache', match: '**\/api/**' });
* ```
*
* @param options
*/
routeFromCache(options: {
/**
* Directory used to store and read cached responses.
*/
dir: string;

/**
* A glob pattern, regex or [URLPattern] that selects which request URLs are cached. When omitted, all `GET` requests
* are cached. Only `GET` requests are ever cached.
*/
match?: string|RegExp|URLPattern;
}): Promise<Disposable>;

/**
* If specified the network requests that are made in the page will be served from the HAR file. Read more about
* [Replaying from HAR](https://playwright.dev/docs/mock#replaying-from-har).
Expand Down Expand Up @@ -10226,6 +10265,42 @@ export interface BrowserContext {
times?: number;
}): Promise<Disposable>;

/**
* Caches responses for matching network requests on disk and replays them on subsequent runs.
*
* On the first run every matching request goes to the network and its response (status, headers and body) is stored
* under [`dir`](https://playwright.dev/docs/api/class-browsercontext#browser-context-route-from-cache-option-dir). On
* later runs matching requests are served from disk without hitting the network. Non-matching requests are left
* untouched.
*
* Responses are stored compactly: small bodies are inlined into a single append-only index, while large bodies are
* content-addressed and de-duplicated in a `blobs/` sub-directory. Only successful (`2xx`) responses are cached;
* other responses always go to the network.
*
* **Usage**
*
* ```js
* // Record on the first run, replay from disk afterwards.
* await context.routeFromCache({ dir: '.cache' });
* const page = await context.newPage();
* await page.goto('https://github.com/microsoft/playwright/issues');
* ```
*
* @param options
*/
routeFromCache(options: {
/**
* Directory used to store and read cached responses.
*/
dir: string;

/**
* A glob pattern, regex or [URLPattern] that selects which request URLs are cached. When omitted, all `GET` requests
* are cached. Only `GET` requests are ever cached.
*/
match?: string|RegExp|URLPattern;
}): Promise<Disposable>;

/**
* If specified the network requests that are made in the context will be served from the HAR file. Read more about
* [Replaying from HAR](https://playwright.dev/docs/mock#replaying-from-har).
Expand Down
7 changes: 6 additions & 1 deletion packages/playwright-core/src/client/browserContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import fs from 'fs';
import path from 'path';

import { headersObjectToArray } from '@isomorphic/headers';
import { urlMatchesEqual } from '@isomorphic/urlMatch';
import { serializeURLMatch, urlMatchesEqual } from '@isomorphic/urlMatch';
import { isRegExp, isString } from '@isomorphic/rtti';
import { rewriteErrorMessage } from '@utils/stackTrace';
import { Browser } from './browser';
Expand Down Expand Up @@ -387,6 +387,11 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>
await this._updateWebSocketInterceptionPatterns({ title: 'Route WebSockets' });
}

async routeFromCache(options: { dir: string, match?: URLMatch }): Promise<DisposableStub> {
const { registrationId } = await this._channel.routeFromCache({ dir: options.dir, url: options.match ? serializeURLMatch(options.match) : undefined }, undefined);
return new DisposableStub(() => this._channel.unrouteFromCache({ registrationId }, undefined).then(() => {}));
}

async routeFromHAR(har: string, options: { url?: string | RegExp, notFound?: 'abort' | 'fallback', update?: boolean, updateContent?: 'attach' | 'embed', updateMode?: 'minimal' | 'full', interceptAPIRequests?: boolean } = {}): Promise<void> {
const localUtils = this._connection.localUtils();
if (!localUtils)
Expand Down
58 changes: 58 additions & 0 deletions packages/playwright-core/src/client/channels.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1282,6 +1282,8 @@ export interface BrowserContextChannel extends BrowserContextEventTarget, Channe
setGeolocation(params: BrowserContextSetGeolocationParams, signal: AbortSignal | undefined): Promise<BrowserContextSetGeolocationResult>;
setHTTPCredentials(params: BrowserContextSetHTTPCredentialsParams, signal: AbortSignal | undefined): Promise<BrowserContextSetHTTPCredentialsResult>;
setNetworkInterceptionPatterns(params: BrowserContextSetNetworkInterceptionPatternsParams, signal: AbortSignal | undefined): Promise<BrowserContextSetNetworkInterceptionPatternsResult>;
routeFromCache(params: BrowserContextRouteFromCacheParams, signal: AbortSignal | undefined): Promise<BrowserContextRouteFromCacheResult>;
unrouteFromCache(params: BrowserContextUnrouteFromCacheParams, signal: AbortSignal | undefined): Promise<BrowserContextUnrouteFromCacheResult>;
routeAPIRequestsFromHar(params: BrowserContextRouteAPIRequestsFromHarParams, signal: AbortSignal | undefined): Promise<BrowserContextRouteAPIRequestsFromHarResult>;
unrouteAPIRequestsFromHar(params: BrowserContextUnrouteAPIRequestsFromHarParams, signal: AbortSignal | undefined): Promise<BrowserContextUnrouteAPIRequestsFromHarResult>;
setWebSocketInterceptionPatterns(params: BrowserContextSetWebSocketInterceptionPatternsParams, signal: AbortSignal | undefined): Promise<BrowserContextSetWebSocketInterceptionPatternsResult>;
Expand Down Expand Up @@ -1517,6 +1519,33 @@ export type BrowserContextSetNetworkInterceptionPatternsOptions = {

};
export type BrowserContextSetNetworkInterceptionPatternsResult = void;
export type BrowserContextRouteFromCacheParams = {
dir: string,
url?: {
glob?: string,
regexSource?: string,
regexFlags?: string,
urlPattern?: URLPattern,
},
};
export type BrowserContextRouteFromCacheOptions = {
url?: {
glob?: string,
regexSource?: string,
regexFlags?: string,
urlPattern?: URLPattern,
},
};
export type BrowserContextRouteFromCacheResult = {
registrationId: string,
};
export type BrowserContextUnrouteFromCacheParams = {
registrationId: string,
};
export type BrowserContextUnrouteFromCacheOptions = {

};
export type BrowserContextUnrouteFromCacheResult = void;
export type BrowserContextRouteAPIRequestsFromHarParams = {
harId: string,
urlGlob?: string,
Expand Down Expand Up @@ -3967,6 +3996,8 @@ export interface PageChannel extends PageEventTarget, Channel {
screenshot(params: PageScreenshotParams, signal: AbortSignal | undefined): Promise<PageScreenshotResult>;
setExtraHTTPHeaders(params: PageSetExtraHTTPHeadersParams, signal: AbortSignal | undefined): Promise<PageSetExtraHTTPHeadersResult>;
setNetworkInterceptionPatterns(params: PageSetNetworkInterceptionPatternsParams, signal: AbortSignal | undefined): Promise<PageSetNetworkInterceptionPatternsResult>;
routeFromCache(params: PageRouteFromCacheParams, signal: AbortSignal | undefined): Promise<PageRouteFromCacheResult>;
unrouteFromCache(params: PageUnrouteFromCacheParams, signal: AbortSignal | undefined): Promise<PageUnrouteFromCacheResult>;
setWebSocketInterceptionPatterns(params: PageSetWebSocketInterceptionPatternsParams, signal: AbortSignal | undefined): Promise<PageSetWebSocketInterceptionPatternsResult>;
setViewportSize(params: PageSetViewportSizeParams, signal: AbortSignal | undefined): Promise<PageSetViewportSizeResult>;
keyboardDown(params: PageKeyboardDownParams, signal: AbortSignal | undefined): Promise<PageKeyboardDownResult>;
Expand Down Expand Up @@ -4292,6 +4323,33 @@ export type PageSetNetworkInterceptionPatternsOptions = {

};
export type PageSetNetworkInterceptionPatternsResult = void;
export type PageRouteFromCacheParams = {
dir: string,
url?: {
glob?: string,
regexSource?: string,
regexFlags?: string,
urlPattern?: URLPattern,
},
};
export type PageRouteFromCacheOptions = {
url?: {
glob?: string,
regexSource?: string,
regexFlags?: string,
urlPattern?: URLPattern,
},
};
export type PageRouteFromCacheResult = {
registrationId: string,
};
export type PageUnrouteFromCacheParams = {
registrationId: string,
};
export type PageUnrouteFromCacheOptions = {

};
export type PageUnrouteFromCacheResult = void;
export type PageSetWebSocketInterceptionPatternsParams = {
patterns: {
glob?: string,
Expand Down
7 changes: 6 additions & 1 deletion packages/playwright-core/src/client/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import path from 'path';
import { assert } from '@isomorphic/assert';
import { headersObjectToArray } from '@isomorphic/headers';
import { trimStringWithEllipsis } from '@isomorphic/stringUtils';
import { urlMatches, urlMatchesEqual } from '@isomorphic/urlMatch';
import { serializeURLMatch, urlMatches, urlMatchesEqual } from '@isomorphic/urlMatch';
import { LongStandingScope } from '@isomorphic/manualPromise';
import { isObject, isRegExp, isString } from '@isomorphic/rtti';
import { Artifact } from './artifact';
Expand Down Expand Up @@ -544,6 +544,11 @@ export class Page extends ChannelOwner<channels.PageChannel> implements api.Page
return new DisposableStub(() => this.unroute(url, handler));
}

async routeFromCache(options: { dir: string, match?: URLMatch }): Promise<DisposableStub> {
const { registrationId } = await this._channel.routeFromCache({ dir: options.dir, url: options.match ? serializeURLMatch(options.match) : undefined }, undefined);
return new DisposableStub(() => this._channel.unrouteFromCache({ registrationId }, undefined).then(() => {}));
}

async routeFromHAR(har: string, options: { url?: string | RegExp, notFound?: 'abort' | 'fallback', update?: boolean, updateContent?: 'attach' | 'embed', updateMode?: 'minimal' | 'full'} = {}): Promise<void> {
const localUtils = this._connection.localUtils();
if (!localUtils)
Expand Down
58 changes: 58 additions & 0 deletions packages/playwright-core/src/server/channels.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1285,6 +1285,8 @@ export interface BrowserContextChannel extends BrowserContextEventTarget, Channe
setGeolocation(params: BrowserContextSetGeolocationParams, progress: Progress): Promise<BrowserContextSetGeolocationResult>;
setHTTPCredentials(params: BrowserContextSetHTTPCredentialsParams, progress: Progress): Promise<BrowserContextSetHTTPCredentialsResult>;
setNetworkInterceptionPatterns(params: BrowserContextSetNetworkInterceptionPatternsParams, progress: Progress): Promise<BrowserContextSetNetworkInterceptionPatternsResult>;
routeFromCache(params: BrowserContextRouteFromCacheParams, progress: Progress): Promise<BrowserContextRouteFromCacheResult>;
unrouteFromCache(params: BrowserContextUnrouteFromCacheParams, progress: Progress): Promise<BrowserContextUnrouteFromCacheResult>;
routeAPIRequestsFromHar(params: BrowserContextRouteAPIRequestsFromHarParams, progress: Progress): Promise<BrowserContextRouteAPIRequestsFromHarResult>;
unrouteAPIRequestsFromHar(params: BrowserContextUnrouteAPIRequestsFromHarParams, progress: Progress): Promise<BrowserContextUnrouteAPIRequestsFromHarResult>;
setWebSocketInterceptionPatterns(params: BrowserContextSetWebSocketInterceptionPatternsParams, progress: Progress): Promise<BrowserContextSetWebSocketInterceptionPatternsResult>;
Expand Down Expand Up @@ -1520,6 +1522,33 @@ export type BrowserContextSetNetworkInterceptionPatternsOptions = {

};
export type BrowserContextSetNetworkInterceptionPatternsResult = void;
export type BrowserContextRouteFromCacheParams = {
dir: string,
url?: {
glob?: string,
regexSource?: string,
regexFlags?: string,
urlPattern?: URLPattern,
},
};
export type BrowserContextRouteFromCacheOptions = {
url?: {
glob?: string,
regexSource?: string,
regexFlags?: string,
urlPattern?: URLPattern,
},
};
export type BrowserContextRouteFromCacheResult = {
registrationId: string,
};
export type BrowserContextUnrouteFromCacheParams = {
registrationId: string,
};
export type BrowserContextUnrouteFromCacheOptions = {

};
export type BrowserContextUnrouteFromCacheResult = void;
export type BrowserContextRouteAPIRequestsFromHarParams = {
harId: string,
urlGlob?: string,
Expand Down Expand Up @@ -3970,6 +3999,8 @@ export interface PageChannel extends PageEventTarget, Channel {
screenshot(params: PageScreenshotParams, progress: Progress): Promise<PageScreenshotResult>;
setExtraHTTPHeaders(params: PageSetExtraHTTPHeadersParams, progress: Progress): Promise<PageSetExtraHTTPHeadersResult>;
setNetworkInterceptionPatterns(params: PageSetNetworkInterceptionPatternsParams, progress: Progress): Promise<PageSetNetworkInterceptionPatternsResult>;
routeFromCache(params: PageRouteFromCacheParams, progress: Progress): Promise<PageRouteFromCacheResult>;
unrouteFromCache(params: PageUnrouteFromCacheParams, progress: Progress): Promise<PageUnrouteFromCacheResult>;
setWebSocketInterceptionPatterns(params: PageSetWebSocketInterceptionPatternsParams, progress: Progress): Promise<PageSetWebSocketInterceptionPatternsResult>;
setViewportSize(params: PageSetViewportSizeParams, progress: Progress): Promise<PageSetViewportSizeResult>;
keyboardDown(params: PageKeyboardDownParams, progress: Progress): Promise<PageKeyboardDownResult>;
Expand Down Expand Up @@ -4295,6 +4326,33 @@ export type PageSetNetworkInterceptionPatternsOptions = {

};
export type PageSetNetworkInterceptionPatternsResult = void;
export type PageRouteFromCacheParams = {
dir: string,
url?: {
glob?: string,
regexSource?: string,
regexFlags?: string,
urlPattern?: URLPattern,
},
};
export type PageRouteFromCacheOptions = {
url?: {
glob?: string,
regexSource?: string,
regexFlags?: string,
urlPattern?: URLPattern,
},
};
export type PageRouteFromCacheResult = {
registrationId: string,
};
export type PageUnrouteFromCacheParams = {
registrationId: string,
};
export type PageUnrouteFromCacheOptions = {

};
export type PageUnrouteFromCacheResult = void;
export type PageSetWebSocketInterceptionPatternsParams = {
patterns: {
glob?: string,
Expand Down
Loading
Loading