Skip to content

Commit c453851

Browse files
authored
api: introduce BrowserType with a single interface, update top-level api (#636)
1 parent 199d094 commit c453851

File tree

13 files changed

+341
-408
lines changed

13 files changed

+341
-408
lines changed

README.md

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,15 @@ Playwright can be used to create a browser instance, open pages, and then manipu
3939
This code snippet navigates to whatsmyuseragent.org in Chromium, Firefox and WebKit, and saves 3 screenshots.
4040

4141
```js
42-
const pw = require('playwright');
42+
const playwright = require('playwright');
4343

4444
(async () => {
45-
for (const name of ['chromium', 'firefox', 'webkit']) {
46-
const browser = await pw[name].launch();
45+
for (const browserType of ['chromium', 'firefox', 'webkit']) {
46+
const browser = await playwright[browserType].launch();
4747
const context = await browser.newContext();
4848
const page = await context.newPage('http://whatsmyuseragent.org/');
49-
50-
await page.screenshot({ path: `example-${name}.png` });
49+
50+
await page.screenshot({ path: `example-${browserType}.png` });
5151
await browser.close();
5252
}
5353
})();
@@ -58,11 +58,11 @@ const pw = require('playwright');
5858
This snippet emulates Mobile Safari on a device at a given geolocation, navigates to maps.google.com, performs action and takes a screenshot.
5959

6060
```js
61-
const pw = require('playwright');
62-
const iPhone11 = pw.devices['iPhone 11 Pro'];
61+
const { webkit, devices } = require('playwright');
62+
const iPhone11 = devices['iPhone 11 Pro'];
6363

6464
(async () => {
65-
const browser = await pw.webkit.launch();
65+
const browser = await webkit.launch();
6666
const context = await browser.newContext({
6767
viewport: iPhone11.viewport,
6868
userAgent: iPhone11.userAgent,
@@ -73,19 +73,19 @@ const iPhone11 = pw.devices['iPhone 11 Pro'];
7373
const page = await context.newPage('https://maps.google.com');
7474
await page.click('text="Your location"');
7575
await page.waitForRequest(/.*preview\/pwa/);
76-
await page.screenshot({ path: 'colosseum-iphone.png' });
76+
await page.screenshot({ path: 'colosseum-iphone.png' });
7777
await browser.close();
7878
})();
7979
```
8080

8181
And here is the same script for Chrome on Android.
8282

8383
```js
84-
const pw = require('playwright');
85-
const pixel2 = pw.devices['Pixel 2'];
84+
const { chromium, devices } = require('playwright');
85+
const pixel2 = devices['Pixel 2'];
8686

8787
(async () => {
88-
const browser = await pw.chromium.launch();
88+
const browser = await chromium.launch();
8989
const context = await browser.newContext({
9090
viewport: pixel2.viewport,
9191
userAgent: pixel2.userAgent,
@@ -106,10 +106,10 @@ const pixel2 = pw.devices['Pixel 2'];
106106
This code snippet navigates to example.com in Firefox, and executes a script in the page context.
107107

108108
```js
109-
const pw = require('playwright');
109+
const { firefox } = require('playwright');
110110

111111
(async () => {
112-
const browser = await pw.firefox.launch(); // or 'chromium', 'webkit'
112+
const browser = await firefox.launch();
113113
const context = await browser.newContext();
114114
const page = await context.newPage();
115115

docs/api.md

Lines changed: 214 additions & 287 deletions
Large diffs are not rendered by default.

docs/web.md

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,7 @@ Playwright contains a version bundled for web browsers under `playwright/web.js`
44
installs playwright under `window.playwrightweb`.
55
You can use it in the web page to drive another browser instance.
66

7-
API consists of a single `connect` function, similar to
8-
[chromiumPlaywright.connect(options)](api.md#chromiumplaywrightconnectoptions),
9-
[firefoxPlaywright.connect(options)](api.md#firefoxplaywrightconnectoptions) and
10-
[webkitPlaywright.connect(options)](api.md#webkitplaywrightconnectoptions).
7+
API consists of a single `connect` function, similar to [browserType.connect(options)](api.md#browsertypeconnectoptions).
118

129
```html
1310
<script src='playwright/web.js'></script>

download-browser.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@
1515
*/
1616

1717
async function downloadBrowser(browser) {
18-
const playwright = require('.')[browser];
18+
const browserType = require('.')[browser];
1919
let progressBar = null;
2020
let lastDownloadedBytes = 0;
2121
function onProgress(downloadedBytes, totalBytes) {
2222
if (!progressBar) {
2323
const ProgressBar = require('progress');
24-
progressBar = new ProgressBar(`Downloading ${browser} ${playwright._revision} - ${toMegabytes(totalBytes)} [:bar] :percent :etas `, {
24+
progressBar = new ProgressBar(`Downloading ${browser} ${browserType._revision} - ${toMegabytes(totalBytes)} [:bar] :percent :etas `, {
2525
complete: '=',
2626
incomplete: ' ',
2727
width: 20,
@@ -33,7 +33,7 @@ async function downloadBrowser(browser) {
3333
progressBar.tick(delta);
3434
}
3535

36-
const fetcher = playwright._createBrowserFetcher();
36+
const fetcher = browserType._createBrowserFetcher();
3737
const revisionInfo = fetcher.revisionInfo();
3838
// Do nothing if the revision is already downloaded.
3939
if (revisionInfo.local)

index.d.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515
*/
1616

1717
export * from './lib/api';
18-
export const chromium: import('./lib/api').ChromiumPlaywright;
19-
export const firefox: import('./lib/api').FirefoxPlaywright;
20-
export const webkit: import('./lib/api').WebKitPlaywright;
18+
export const devices: typeof import('./lib/deviceDescriptors').DeviceDescriptors;
19+
export const errors: { TimeoutError: typeof import('./lib/errors').TimeoutError };
20+
export const chromium: import('./lib/api').Chromium;
21+
export const firefox: import('./lib/api').Firefox;
22+
export const webkit: import('./lib/api').WebKit;
2123
export type PlaywrightWeb = typeof import('./lib/web');

index.js

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,21 @@
1717
const { helper } = require('./lib/helper');
1818
const api = require('./lib/api');
1919
const packageJson = require('./package.json');
20-
const { DeviceDescriptors } = require('./lib/deviceDescriptors');
20+
const DeviceDescriptors = require('./lib/deviceDescriptors');
21+
const { TimeoutError } = require('./lib/errors');
22+
const { Chromium } = require('./lib/server/chromium');
23+
const { Firefox } = require('./lib/server/firefox');
24+
const { WebKit } = require('./lib/server/webkit');
2125

2226
for (const className in api) {
2327
if (typeof api[className] === 'function')
2428
helper.installApiHooks(className, api[className]);
2529
}
2630

2731
module.exports = {
28-
chromium: new api.ChromiumPlaywright(__dirname, packageJson.playwright.chromium_revision),
29-
firefox: new api.FirefoxPlaywright(__dirname, packageJson.playwright.firefox_revision),
30-
webkit: new api.WebKitPlaywright(__dirname, packageJson.playwright.webkit_revision),
31-
devices: DeviceDescriptors
32-
};
32+
devices: DeviceDescriptors,
33+
errors: { TimeoutError },
34+
chromium: new Chromium(__dirname, packageJson.playwright.chromium_revision),
35+
firefox: new Firefox(__dirname, packageJson.playwright.firefox_revision),
36+
webkit: new WebKit(__dirname, packageJson.playwright.webkit_revision),
37+
}

prepare.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,7 @@ async function downloadAndCleanup(browser) {
5454
const revisionInfo = await downloadBrowser(browser);
5555

5656
// Remove previous revisions.
57-
const playwright = require('.')[browser];
58-
const fetcher = playwright._createBrowserFetcher();
57+
const fetcher = require('.')[browser]._createBrowserFetcher();
5958
const localRevisions = await fetcher.localRevisions();
6059
const cleanupOldVersions = localRevisions.filter(revision => revision !== revisionInfo.revision).map(revision => fetcher.remove(revision));
6160
await Promise.all([...cleanupOldVersions]);

src/api.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,5 @@ export { FFBrowser as FirefoxBrowser } from './firefox/ffBrowser';
3535

3636
export { WKBrowser as WebKitBrowser } from './webkit/wkBrowser';
3737

38-
export { Playwright } from './server/playwright';
38+
export { BrowserType } from './server/browserType';
3939
export { BrowserApp } from './server/browserApp';
40-
export { CRPlaywright as ChromiumPlaywright } from './server/crPlaywright';
41-
export { FFPlaywright as FirefoxPlaywright } from './server/ffPlaywright';
42-
export { WKPlaywright as WebKitPlaywright } from './server/wkPlaywright';

src/server/browserType.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Copyright (c) Microsoft Corporation.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import * as types from '../types';
18+
import { TimeoutError } from '../errors';
19+
import { Browser, ConnectOptions } from '../browser';
20+
import { BrowserApp } from './browserApp';
21+
22+
export type BrowserArgOptions = {
23+
headless?: boolean,
24+
args?: string[],
25+
userDataDir?: string,
26+
devtools?: boolean,
27+
};
28+
29+
export type LaunchOptions = BrowserArgOptions & {
30+
executablePath?: string,
31+
ignoreDefaultArgs?: boolean | string[],
32+
handleSIGINT?: boolean,
33+
handleSIGTERM?: boolean,
34+
handleSIGHUP?: boolean,
35+
timeout?: number,
36+
dumpio?: boolean,
37+
env?: {[key: string]: string} | undefined,
38+
webSocket?: boolean,
39+
slowMo?: number, // TODO: we probably don't want this in launchBrowserApp.
40+
};
41+
42+
export interface BrowserType {
43+
executablePath(): string;
44+
launchBrowserApp(options?: LaunchOptions): Promise<BrowserApp>;
45+
launch(options?: LaunchOptions): Promise<Browser>;
46+
defaultArgs(options?: BrowserArgOptions): string[];
47+
connect(options: ConnectOptions & { browserURL?: string }): Promise<Browser>;
48+
devices: types.Devices;
49+
errors: { TimeoutError: typeof TimeoutError };
50+
}

src/server/crPlaywright.ts renamed to src/server/chromium.ts

Lines changed: 3 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -29,34 +29,11 @@ import { TimeoutError } from '../errors';
2929
import { launchProcess, waitForLine } from '../server/processLauncher';
3030
import { kBrowserCloseMessageId } from '../chromium/crConnection';
3131
import { PipeTransport } from './pipeTransport';
32-
import { Playwright } from './playwright';
32+
import { LaunchOptions, BrowserArgOptions, BrowserType } from './browserType';
3333
import { createTransport, ConnectOptions } from '../browser';
3434
import { BrowserApp } from './browserApp';
3535

36-
export type SlowMoOptions = {
37-
slowMo?: number,
38-
};
39-
40-
export type ChromiumArgOptions = {
41-
headless?: boolean,
42-
args?: string[],
43-
userDataDir?: string,
44-
devtools?: boolean,
45-
};
46-
47-
export type LaunchOptions = ChromiumArgOptions & SlowMoOptions & {
48-
executablePath?: string,
49-
ignoreDefaultArgs?: boolean | string[],
50-
handleSIGINT?: boolean,
51-
handleSIGTERM?: boolean,
52-
handleSIGHUP?: boolean,
53-
timeout?: number,
54-
dumpio?: boolean,
55-
env?: {[key: string]: string} | undefined,
56-
webSocket?: boolean,
57-
};
58-
59-
export class CRPlaywright implements Playwright {
36+
export class Chromium implements BrowserType {
6037
private _projectRoot: string;
6138
readonly _revision: string;
6239

@@ -184,7 +161,7 @@ export class CRPlaywright implements Playwright {
184161
return { TimeoutError };
185162
}
186163

187-
defaultArgs(options: ChromiumArgOptions = {}): string[] {
164+
defaultArgs(options: BrowserArgOptions = {}): string[] {
188165
const {
189166
devtools = false,
190167
headless = !devtools,

0 commit comments

Comments
 (0)