Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add allow/block serviceWorkers option #14714

Merged
merged 4 commits into from
Jun 8, 2022
Merged
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
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
6 changes: 6 additions & 0 deletions 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 @@ -3983,6 +3987,7 @@ export type AndroidDeviceLaunchBrowserParams = {
},
recordHar?: RecordHarOptions,
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
pkg?: string,
proxy?: {
server: string,
Expand Down Expand Up @@ -4036,6 +4041,7 @@ export type AndroidDeviceLaunchBrowserOptions = {
},
recordHar?: RecordHarOptions,
strictSelectors?: boolean,
serviceWorkers?: 'allow' | 'block',
pkg?: string,
proxy?: {
server: string,
Expand Down
5 changes: 5 additions & 0 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
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
2 changes: 2 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,8 @@ export abstract class BrowserContext extends SdkObject {

if (debugMode() === 'console')
await this.extendInjectedScript(consoleApiSource.source);
if (this._options.serviceWorkers === 'block')
await this.addInitScript(`\nnavigator.serviceWorker.register = () => { console.warn('Service Worker registration blocked by Playwright'); };\n`);
}

async _ensureVideosPath() {
Expand Down
1 change: 1 addition & 0 deletions packages/playwright-core/src/server/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ export type BrowserContextOptions = {
strictSelectors?: boolean,
proxy?: ProxySettings,
baseURL?: string,
serviceWorkers?: 'allow' | 'block',
};

export type EnvArray = { name: string, value: string }[];
Expand Down
44 changes: 40 additions & 4 deletions packages/playwright-core/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10371,13 +10371,22 @@ export interface BrowserType<Unused = {}> {
height: number;
};

/**
* - `"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"`.
*/
serviceWorkers?: "allow"|"block";

/**
* Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
*/
slowMo?: number;

/**
* It specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
* 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.
*/
Expand Down Expand Up @@ -11528,7 +11537,16 @@ export interface AndroidDevice {
};

/**
* It specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
* - `"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"`.
*/
serviceWorkers?: "allow"|"block";

/**
* 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.
*/
Expand Down Expand Up @@ -13060,6 +13078,15 @@ export interface Browser extends EventEmitter {
height: number;
};

/**
* - `"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"`.
*/
serviceWorkers?: "allow"|"block";

/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
* obtained via
Expand Down Expand Up @@ -13115,7 +13142,7 @@ export interface Browser extends EventEmitter {
};

/**
* It specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
* 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.
*/
Expand Down Expand Up @@ -15515,6 +15542,15 @@ export interface BrowserContextOptions {
height: number;
};

/**
* - `"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"`.
*/
serviceWorkers?: "allow"|"block";

/**
* Populates context with given storage state. This option can be used to initialize context with logged-in information
* obtained via
Expand Down Expand Up @@ -15570,7 +15606,7 @@ export interface BrowserContextOptions {
};

/**
* It specified, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors
* 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.
*/
Expand Down
4 changes: 4 additions & 0 deletions packages/playwright-test/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ export const test = _baseTest.extend<TestFixtures, WorkerFixtures>({
baseURL: [ async ({ }, use) => {
await use(process.env.PLAYWRIGHT_TEST_BASE_URL);
}, { option: true } ],
serviceWorkers: [ 'allow', { option: true } ],
contextOptions: [ {}, { option: true } ],

_combinedContextOptions: async ({
Expand All @@ -183,6 +184,7 @@ export const test = _baseTest.extend<TestFixtures, WorkerFixtures>({
userAgent,
baseURL,
contextOptions,
serviceWorkers,
}, use) => {
const options: BrowserContextOptions = {};
if (acceptDownloads !== undefined)
Expand Down Expand Up @@ -225,6 +227,8 @@ export const test = _baseTest.extend<TestFixtures, WorkerFixtures>({
options.viewport = viewport;
if (baseURL !== undefined)
options.baseURL = baseURL;
if (serviceWorkers !== undefined)
options.serviceWorkers = serviceWorkers;
await use({
...contextOptions,
...options,
Expand Down
1 change: 1 addition & 0 deletions packages/playwright-test/src/mount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ function contextHash(context: BrowserContextOptions): string {
timezoneId: context.timezoneId,
userAgent: context.userAgent,
deviceScaleFactor: context.deviceScaleFactor,
serviceWorkers: context.serviceWorkers,
};
return JSON.stringify(hash);
}
9 changes: 9 additions & 0 deletions packages/playwright-test/types/test.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2494,6 +2494,7 @@ type ColorScheme = Exclude<BrowserContextOptions['colorScheme'], undefined>;
type ExtraHTTPHeaders = Exclude<BrowserContextOptions['extraHTTPHeaders'], undefined>;
type Proxy = Exclude<BrowserContextOptions['proxy'], undefined>;
type StorageState = Exclude<BrowserContextOptions['storageState'], undefined>;
type ServiceWorkerPolicy = Exclude<BrowserContextOptions['serviceWorkers'], undefined>;
type ConnectOptions = {
/**
* A browser websocket endpoint to connect to.
Expand Down Expand Up @@ -2798,6 +2799,14 @@ export interface PlaywrightTestOptions {
* Learn more about [various timeouts](https://playwright.dev/docs/test-timeouts).
*/
navigationTimeout: number | undefined;
/**
* - `"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"`.
*/
serviceWorkers: ServiceWorkerPolicy | undefined;
}


Expand Down
32 changes: 32 additions & 0 deletions tests/library/browsercontext-service-worker-policy.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { browserTest as it, expect } from '../config/browserTest';

it('should allow service workers by default', async ({ page, server }) => {
await page.goto(server.PREFIX + '/serviceworkers/empty/sw.html');
await expect(page.evaluate(() => window['registrationPromise'])).resolves.toBeTruthy();
});

it.describe('block', () => {
it.use({ serviceWorkers: 'block' });

it('blocks service worker registration', async ({ page, server }) => {
await Promise.all([
page.waitForEvent('console', evt => evt.text() === 'Service Worker registration blocked by Playwright'),
page.goto(server.PREFIX + '/serviceworkers/empty/sw.html'),
]);
});
});
2 changes: 2 additions & 0 deletions utils/generate_types/overrides-test.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ type ColorScheme = Exclude<BrowserContextOptions['colorScheme'], undefined>;
type ExtraHTTPHeaders = Exclude<BrowserContextOptions['extraHTTPHeaders'], undefined>;
type Proxy = Exclude<BrowserContextOptions['proxy'], undefined>;
type StorageState = Exclude<BrowserContextOptions['storageState'], undefined>;
type ServiceWorkerPolicy = Exclude<BrowserContextOptions['serviceWorkers'], undefined>;
type ConnectOptions = {
/**
* A browser websocket endpoint to connect to.
Expand Down Expand Up @@ -231,6 +232,7 @@ export interface PlaywrightTestOptions {
contextOptions: BrowserContextOptions;
actionTimeout: number | undefined;
navigationTimeout: number | undefined;
serviceWorkers: ServiceWorkerPolicy | undefined;
}


Expand Down