Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
99fa408
feat: service worker plumbing
rwoll May 21, 2022
1e904fd
test.fail does not work with timedout tests
rwoll May 21, 2022
92e28e0
add SW fetch interception test
rwoll May 21, 2022
2e62e69
feat: add serviceWorkerPolicy option
rwoll May 31, 2022
1d11c99
lint
rwoll May 31, 2022
c834407
add Response.isFromServiceWorker
rwoll May 31, 2022
3a32f3e
Merge branch 'feat/swp' into feature/service-worker-support
rwoll May 31, 2022
7f9f9ce
add serviceWorkerPolicy for opt-in SW networking
rwoll May 31, 2022
8200a67
update docs
rwoll Jun 1, 2022
36b2e6d
tests: make port agnostic, skip SW on older CR versions
rwoll Jun 1, 2022
29927e9
lint
rwoll Jun 1, 2022
fd3c1f8
fix serviceWorkerPolicy
rwoll Jun 1, 2022
a3fc930
remove isServiceWorker
rwoll Jun 1, 2022
c85e6a8
s/isFromServiceWorker/fulfilledByServiceWorker
rwoll Jun 1, 2022
0a156d8
simplify and document serviceWorkerPolicy
rwoll Jun 1, 2022
d1a91e8
fix lint error
rwoll Jun 1, 2022
6a0931b
s/_needsRequestInterception/needsRequestInterception
rwoll Jun 1, 2022
7c7fd2f
wip: setOffline, HTTP Creds, extra headers
rwoll Jun 1, 2022
790e879
fix HTTP Creds test
rwoll Jun 1, 2022
6655ad9
race with SW close
rwoll Jun 2, 2022
855b5a8
s/inspected/enable-network-events
rwoll Jun 2, 2022
87b84a0
fix rename
rwoll Jun 2, 2022
61124fb
Merge branch 'main' into feature/service-worker-support
rwoll Jun 2, 2022
3965412
stall sw when policy is disabled
rwoll Jun 2, 2022
d7642ec
make fulfilledByServiceWorker non-nullable (albeit broken on WK and F…
rwoll Jun 2, 2022
cf6ab16
add fulfilledByServiceWorker test for all browsers, support WK
rwoll Jun 3, 2022
406becc
remove invalid CORS test
rwoll Jun 3, 2022
c483eac
opt-in by default, s/serviceWorkersPolicy/serviceWorkers, reduce options
rwoll Jun 3, 2022
63d9375
update docs
rwoll Jun 3, 2022
562bc0b
link upstream patch in fixme
rwoll Jun 3, 2022
2150843
Merge branch 'main' into feature/service-worker-support
rwoll Jun 8, 2022
3239e79
add FF fulfilledByServiceWorker impl
rwoll Jun 8, 2022
8f6c549
fix FF expectation
rwoll Jun 8, 2022
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
9 changes: 9 additions & 0 deletions docs/src/api/class-request.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,15 @@ following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttr

Returns the matching [Response] object, or `null` if the response was not received due to error.

## method: Request.serviceWorker
- returns: <[null]|[Worker]>

:::note
This field is Chromium only. It's safe to call when using other browsers, but it will always be `null`.
:::

The Service [Worker] that is performing the request.

## async method: Request.sizes
- returns: <[Object]>
- `requestBodySize` <[int]> Size of the request body (POST data payload) in bytes. Set to 0 if there was no body.
Expand Down
5 changes: 5 additions & 0 deletions docs/src/api/class-response.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ Waits for this response to finish, returns always `null`.

Returns the [Frame] that initiated this response.

## method: Response.fulfilledByServiceWorker
- returns: <[boolean]>

Indicates whether this Response was fullfilled by a Service Worker's Fetch Handler (i.e. via [FetchEvent.respondWith](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith)).

## method: Response.headers
- returns: <[Object]<[string], [string]>>

Expand Down
12 changes: 10 additions & 2 deletions docs/src/api/params.md
Original file line number Diff line number Diff line change
Expand Up @@ -637,10 +637,18 @@ contexts override the proxy, global proxy will be never used and can be any stri
## context-option-strict
- `strictSelectors` <[boolean]>

It specified, enables strict selectors mode for this context. In the strict selectors mode all operations
If specified, enables strict selectors mode for this context. In the strict selectors mode all operations
on selectors that imply single target DOM element will throw when more than one element matches the selector.
See [Locator] to learn more about the strict mode.

## context-option-service-worker-policy
- `serviceWorkers` <[ServiceWorkerPolicy]<"allow"|"block">>

* `"allow"`: [Service Workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can be registered by sites.
* `"block"`: Playwright will block all registration of Service Workers.

Defaults to `"allow"`.

## select-options-values
* langs: java, js, csharp
- `values` <[null]|[string]|[ElementHandle]|[Array]<[string]>|[Object]|[Array]<[ElementHandle]>|[Array]<[Object]>>
Expand Down Expand Up @@ -796,6 +804,7 @@ An acceptable perceived color difference in the [YIQ color space](https://en.wik
- %%-context-option-recordvideo-dir-%%
- %%-context-option-recordvideo-size-%%
- %%-context-option-strict-%%
- %%-context-option-service-worker-policy-%%

## browser-option-args
- `args` <[Array]<[string]>>
Expand Down Expand Up @@ -1020,4 +1029,3 @@ When set to `"hide"`, screenshot will hide text caret. When set to `"initial"`,
- %%-screenshot-option-type-%%
- %%-screenshot-option-mask-%%
- %%-input-timeout-%%

1 change: 1 addition & 0 deletions docs/src/test-api/class-testoptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,4 @@ Learn more about [recording video](../test-configuration.md#record-video).

## property: TestOptions.viewport = %%-context-option-viewport-%%

## property: TestOptions.serviceWorkers = %%-context-option-service-worker-policy-%%
1 change: 1 addition & 0 deletions packages/playwright-core/src/client/browserContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,7 @@ export async function prepareBrowserContextParams(options: BrowserContextOptions
noDefaultViewport: options.viewport === null,
extraHTTPHeaders: options.extraHTTPHeaders ? headersObjectToArray(options.extraHTTPHeaders) : undefined,
storageState: await prepareStorageState(options),
serviceWorkers: options.serviceWorkers,
recordHar: prepareRecordHarOptions(options.recordHar),
};
if (!contextParams.recordVideo && options.videosPath) {
Expand Down
26 changes: 19 additions & 7 deletions packages/playwright-core/src/client/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ import { URLSearchParams } from 'url';
import type * as channels from '../protocol/channels';
import { ChannelOwner } from './channelOwner';
import { Frame } from './frame';
import { Worker } from './worker';
import type { Headers, RemoteAddr, SecurityDetails, WaitForEventOptions } from './types';
import fs from 'fs';
import { mime } from '../utilsBundle';
import { isString, headersObjectToArray } from '../utils';
import { isString, headersObjectToArray, assert } from '../utils';
import { ManualPromise } from '../utils/manualPromise';
import { Events } from './events';
import type { Page } from './page';
Expand Down Expand Up @@ -172,9 +173,17 @@ export class Request extends ChannelOwner<channels.RequestChannel> implements ap
}

frame(): Frame {
if (!this._initializer.frame) {
assert(this.serviceWorker());
throw new Error('Service Worker requests do not have an associated frame.');
Comment thread
rwoll marked this conversation as resolved.
Resolved
}
return Frame.from(this._initializer.frame);
}

serviceWorker(): Worker | null {
return this._initializer.serviceWorker ? Worker.from(this._initializer.serviceWorker) : null;
}

isNavigationRequest(): boolean {
return this._initializer.isNavigationRequest;
}
Expand Down Expand Up @@ -224,19 +233,18 @@ export class Route extends ChannelOwner<channels.RouteChannel> implements api.Ro
return Request.from(this._initializer.request);
}

private _raceWithPageClose(promise: Promise<any>): Promise<void> {
const page = this.request().frame()._page;
private _raceWithTargetClose(promise: Promise<any>): Promise<void> {
// When page closes or crashes, we catch any potential rejects from this Route.
// Note that page could be missing when routing popup's initial request that
// does not have a Page initialized just yet.
return Promise.race([
promise,
page ? page._closedOrCrashedPromise : Promise.resolve(),
this.request().serviceWorker()?._closedPromise || this.request().frame()._page?._closedOrCrashedPromise || Promise.resolve(),
]);
}

async abort(errorCode?: string) {
await this._raceWithPageClose(this._channel.abort({ errorCode }));
await this._raceWithTargetClose(this._channel.abort({ errorCode }));
}

async fulfill(options: { response?: api.APIResponse, status?: number, headers?: Headers, contentType?: string, body?: string | Buffer, path?: string } = {}) {
Expand Down Expand Up @@ -279,7 +287,7 @@ export class Route extends ChannelOwner<channels.RouteChannel> implements api.Ro
if (length && !('content-length' in headers))
headers['content-length'] = String(length);

await this._raceWithPageClose(this._channel.fulfill({
await this._raceWithTargetClose(this._channel.fulfill({
status: statusOption || 200,
headers: headersObjectToArray(headers),
body,
Expand All @@ -299,7 +307,7 @@ export class Route extends ChannelOwner<channels.RouteChannel> implements api.Ro
private async _continue(options: { url?: string, method?: string, headers?: Headers, postData?: string | Buffer }, isInternal?: boolean) {
return await this._wrapApiCall(async () => {
const postDataBuffer = isString(options.postData) ? Buffer.from(options.postData, 'utf8') : options.postData;
await this._raceWithPageClose(this._channel.continue({
await this._raceWithTargetClose(this._channel.continue({
url: options.url,
method: options.method,
headers: options.headers ? headersObjectToArray(options.headers) : undefined,
Expand Down Expand Up @@ -368,6 +376,10 @@ export class Response extends ChannelOwner<channels.ResponseChannel> implements
return this._initializer.statusText;
}

fulfilledByServiceWorker(): boolean {
return this._initializer.fulfilledByServiceWorker;
}

/**
* @deprecated
*/
Expand Down
2 changes: 2 additions & 0 deletions packages/playwright-core/src/client/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import type * as structs from '../../types/structs';
export class Worker extends ChannelOwner<channels.WorkerChannel> implements api.Worker {
_page: Page | undefined; // Set for web workers.
_context: BrowserContext | undefined; // Set for service workers.
_closedPromise: Promise<void>;

static from(worker: channels.WorkerChannel): Worker {
return (worker as any)._object;
Expand All @@ -40,6 +41,7 @@ export class Worker extends ChannelOwner<channels.WorkerChannel> implements api.
this._context._serviceWorkers.delete(this);
this.emit(Events.Worker.Close, this);
});
this._closedPromise = new Promise(f => this.once(Events.Worker.Close, f));
}

url(): string {
Expand Down
10 changes: 9 additions & 1 deletion packages/playwright-core/src/protocol/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,7 @@ export type BrowserTypeLaunchPersistentContextParams = {
},
recordHar?: RecordHarOptions,
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
userDataDir: string,
slowMo?: number,
};
Expand Down Expand Up @@ -816,6 +817,7 @@ export type BrowserTypeLaunchPersistentContextOptions = {
},
recordHar?: RecordHarOptions,
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
slowMo?: number,
};
export type BrowserTypeLaunchPersistentContextResult = {
Expand Down Expand Up @@ -909,6 +911,7 @@ export type BrowserNewContextParams = {
},
recordHar?: RecordHarOptions,
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
proxy?: {
server: string,
bypass?: string,
Expand Down Expand Up @@ -965,6 +968,7 @@ export type BrowserNewContextOptions = {
},
recordHar?: RecordHarOptions,
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
proxy?: {
server: string,
bypass?: string,
Expand Down Expand Up @@ -3083,7 +3087,8 @@ export interface ElementHandleEvents {

// ----------- Request -----------
export type RequestInitializer = {
frame: FrameChannel,
frame?: FrameChannel,
serviceWorker?: WorkerChannel,
url: string,
resourceType: string,
method: string,
Expand Down Expand Up @@ -3183,6 +3188,7 @@ export type ResponseInitializer = {
statusText: string,
headers: NameValue[],
timing: ResourceTiming,
fulfilledByServiceWorker: boolean,
};
export interface ResponseEventTarget {
}
Expand Down Expand Up @@ -3983,6 +3989,7 @@ export type AndroidDeviceLaunchBrowserParams = {
},
recordHar?: RecordHarOptions,
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
pkg?: string,
proxy?: {
server: string,
Expand Down Expand Up @@ -4036,6 +4043,7 @@ export type AndroidDeviceLaunchBrowserOptions = {
},
recordHar?: RecordHarOptions,
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
pkg?: string,
proxy?: {
server: string,
Expand Down
10 changes: 8 additions & 2 deletions packages/playwright-core/src/protocol/protocol.yml
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,11 @@ ContextOptions:
height: number
recordHar: RecordHarOptions?
strictSelectors: boolean?
serviceWorkers:
type: enum?
literals:
- allow
- block

LocalUtils:
type: interface
Expand Down Expand Up @@ -2416,7 +2421,8 @@ Request:
type: interface

initializer:
frame: Frame
frame: Frame?
serviceWorker: Worker?
url: string
resourceType: string
method: string
Expand Down Expand Up @@ -2472,7 +2478,6 @@ Route:
isBase64: boolean?
fetchResponseUid: string?


ResourceTiming:
type: object
properties:
Expand All @@ -2497,6 +2502,7 @@ Response:
type: array
items: NameValue
timing: ResourceTiming
fulfilledByServiceWorker: boolean


commands:
Expand Down
3 changes: 3 additions & 0 deletions packages/playwright-core/src/protocol/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ export function createScheme(tChannel: (name: string) => Validator): Scheme {
})),
recordHar: tOptional(tType('RecordHarOptions')),
strictSelectors: tOptional(tBoolean),
serviceWorkers: tOptional(tEnum(['allow', 'block'])),
userDataDir: tString,
slowMo: tOptional(tNumber),
});
Expand Down Expand Up @@ -410,6 +411,7 @@ export function createScheme(tChannel: (name: string) => Validator): Scheme {
})),
recordHar: tOptional(tType('RecordHarOptions')),
strictSelectors: tOptional(tBoolean),
serviceWorkers: tOptional(tEnum(['allow', 'block'])),
proxy: tOptional(tObject({
server: tString,
bypass: tOptional(tString),
Expand Down Expand Up @@ -1441,6 +1443,7 @@ export function createScheme(tChannel: (name: string) => Validator): Scheme {
})),
recordHar: tOptional(tType('RecordHarOptions')),
strictSelectors: tOptional(tBoolean),
serviceWorkers: tOptional(tEnum(['allow', 'block'])),
pkg: tOptional(tString),
proxy: tOptional(tObject({
server: tString,
Expand Down
15 changes: 15 additions & 0 deletions packages/playwright-core/src/server/browserContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,19 @@ export abstract class BrowserContext extends SdkObject {

if (debugMode() === 'console')
await this.extendInjectedScript(consoleApiSource.source);
if (this._options.serviceWorkers === 'block') {
await this.addInitScript(`

// Service Worker Policy Injected Script

navigator.serviceWorker.register = () => {
console.warn('Service Worker registration blocked by Playwright');
};

// END Service Worker Policy Injected Script

`);
}
}

async _ensureVideosPath() {
Expand Down Expand Up @@ -455,6 +468,8 @@ export function validateBrowserContextOptions(options: types.BrowserContextOptio
throw new Error(`"isMobile" option is not supported with null "viewport"`);
if (options.acceptDownloads === undefined)
options.acceptDownloads = true;
if (options.serviceWorkers === undefined)
options.serviceWorkers = 'allow';
if (!options.viewport && !options.noDefaultViewport)
options.viewport = { width: 1280, height: 720 };
if (options.recordVideo) {
Expand Down
Loading