Skip to content

Commit b43f33f

Browse files
authored
api(review): misc changes to API. (#1356)
1 parent 7fe5656 commit b43f33f

11 files changed

+60
-87
lines changed

docs/api.md

+29-56
Original file line numberDiff line numberDiff line change
@@ -192,15 +192,15 @@ Indicates that the browser is connected.
192192

193193
#### browser.newContext([options])
194194
- `options` <[Object]>
195-
- `ignoreHTTPSErrors` <?[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`.
196-
- `bypassCSP` <?[boolean]> Toggles bypassing page's Content-Security-Policy.
197-
- `viewport` <?[Object]> Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
195+
- `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`.
196+
- `bypassCSP` <[boolean]> Toggles bypassing page's Content-Security-Policy.
197+
- `viewport` <[Object]> Sets a consistent viewport for each page. Defaults to an 1280x720 viewport. `null` disables the default viewport.
198198
- `width` <[number]> page width in pixels.
199199
- `height` <[number]> page height in pixels.
200200
- `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`.
201201
- `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account and touch events are enabled. Defaults to `false`. Not supported in Firefox.
202-
- `userAgent` <?[string]> Specific user agent to use in this context.
203-
- `javaScriptEnabled` <?[boolean]> Whether or not to enable or disable JavaScript in the context. Defaults to true.
202+
- `userAgent` <[string]> Specific user agent to use in this context.
203+
- `javaScriptEnabled` <[boolean]> Whether or not to enable or disable JavaScript in the context. Defaults to true.
204204
- `timezoneId` <?[string]> Changes the timezone of the context. See [ICU’s `metaZones.txt`](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs.
205205
- `geolocation` <[Object]>
206206
- `latitude` <[number]> Latitude between -90 and 90.
@@ -341,10 +341,13 @@ An example of overriding `Math.random` before the page loads:
341341
```js
342342
// preload.js
343343
Math.random = () => 42;
344+
```
344345

345-
// In your playwright script, assuming the preload.js file is in same folder
346-
const preloadFile = fs.readFileSync('./preload.js', 'utf8');
347-
await browserContext.addInitScript(preloadFile);
346+
```js
347+
// In your playwright script, assuming the preload.js file is in same folder.
348+
await browserContext.addInitScript({
349+
path: 'preload.js'
350+
});
348351
```
349352

350353
> **NOTE** The order of evaluation of multiple scripts installed via [browserContext.addInitScript(script[, ...args])](#browsercontextaddinitscriptscript-args) and [page.addInitScript(script[, ...args])](#pageaddinitscriptscript-args) is not defined.
@@ -391,7 +394,7 @@ If URLs are specified, only cookies that affect those URLs are returned.
391394

392395
#### browserContext.exposeFunction(name, playwrightFunction)
393396
- `name` <[string]> Name of the function on the window object.
394-
- `playwrightFunction` <[function]> Callback function which will be called in Playwright's context.
397+
- `playwrightFunction` <[function]> Callback function that will be called in the Playwright's context.
395398
- returns: <[Promise]>
396399

397400
The method adds a function called `name` on the `window` object of every frame in every page in the context.
@@ -426,36 +429,6 @@ const crypto = require('crypto');
426429
})();
427430
```
428431

429-
An example of adding a `window.readfile` function to all pages in the context:
430-
431-
```js
432-
const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
433-
const fs = require('fs');
434-
435-
(async () => {
436-
const browser = await chromium.launch();
437-
const context = await browser.newContext();
438-
await context.exposeFunction('readfile', async filePath => {
439-
return new Promise((resolve, reject) => {
440-
fs.readFile(filePath, 'utf8', (err, text) => {
441-
if (err)
442-
reject(err);
443-
else
444-
resolve(text);
445-
});
446-
});
447-
});
448-
const page = await context.newPage();
449-
page.on('console', msg => console.log(msg.text()));
450-
await page.evaluate(async () => {
451-
// use window.readfile to read contents of a file
452-
const content = await window.readfile('/etc/hosts');
453-
console.log(content);
454-
});
455-
await browser.close();
456-
})();
457-
```
458-
459432
#### browserContext.newPage()
460433
- returns: <[Promise]<[Page]>>
461434

@@ -551,13 +524,13 @@ The extra HTTP headers will be sent with every request initiated by any page in
551524
- `accuracy` <[number]> Optional non-negative accuracy value.
552525
- returns: <[Promise]>
553526

554-
Sets the page's geolocation. Passing null or undefined emulates position unavailable.
527+
Sets the contexts's geolocation. Passing null or undefined emulates position unavailable.
555528

556529
```js
557530
await browserContext.setGeolocation({latitude: 59.95, longitude: 30.31667});
558531
```
559532

560-
> **NOTE** Consider using [browserContext.setPermissions](#browsercontextsetpermissions-permissions) to grant permissions for the page to read its geolocation.
533+
> **NOTE** Consider using [browserContext.setPermissions](#browsercontextsetpermissions-permissions) to grant permissions for the browser context pages to read its geolocation.
561534
562535
#### browserContext.setHTTPCredentials(httpCredentials)
563536
- `httpCredentials` <?[Object]>
@@ -3346,7 +3319,7 @@ Aborts request. To use this, request interception should be enabled with `page.r
33463319
Exception is immediately thrown if the request interception is not enabled.
33473320

33483321
#### request.continue([overrides])
3349-
- `overrides` <[Object]> Optional request overwrites, which can be one of the following:
3322+
- `overrides` <[Object]> Optional request overrides, which can be one of the following:
33503323
- `method` <[string]> If set changes the request method (e.g. GET or POST)
33513324
- `postData` <[string]> If set changes the post data of request
33523325
- `headers` <[Object]> If set changes the request HTTP headers. Header values will be converted to a string.
@@ -3370,10 +3343,10 @@ await page.route('**/*', request => {
33703343
- returns: <?[Object]> Object describing request failure, if any
33713344
- `errorText` <[string]> Human-readable error message, e.g. `'net::ERR_FAILED'`.
33723345

3373-
The method returns `null` unless this request was failed, as reported by
3346+
The method returns `null` unless this request has failed, as reported by
33743347
`requestfailed` event.
33753348

3376-
Example of logging all failed requests:
3349+
Example of logging of all the failed requests:
33773350

33783351
```js
33793352
page.on('requestfailed', request => {
@@ -3473,7 +3446,7 @@ ResourceType will be one of the following: `document`, `stylesheet`, `image`, `m
34733446
[Response] class represents responses which are received by page.
34743447

34753448
<!-- GEN:toc -->
3476-
- [response.buffer()](#responsebuffer)
3449+
- [response.body()](#responsebody)
34773450
- [response.finished()](#responsefinished)
34783451
- [response.frame()](#responseframe)
34793452
- [response.headers()](#responseheaders)
@@ -3486,11 +3459,11 @@ ResourceType will be one of the following: `document`, `stylesheet`, `image`, `m
34863459
- [response.url()](#responseurl)
34873460
<!-- GEN:stop -->
34883461

3489-
#### response.buffer()
3462+
#### response.body()
34903463
- returns: <Promise<[Buffer]>> Promise which resolves to a buffer with response body.
34913464

34923465
#### response.finished()
3493-
- returns: <Promise[?string]> Waits for this response to finish, throws when corresponding request failed.
3466+
- returns: <Promise<?[Error]>> Waits for this response to finish, returns failure error if request failed.
34943467

34953468
#### response.frame()
34963469
- returns: <[Frame]> A [Frame] that initiated this response.
@@ -3743,7 +3716,7 @@ Closes the browser gracefully and makes sure the process is terminated.
37433716
Kills the browser process.
37443717

37453718
#### browserServer.process()
3746-
- returns: <?[ChildProcess]> Spawned browser application process.
3719+
- returns: <[ChildProcess]> Spawned browser application process.
37473720

37483721
#### browserServer.wsEndpoint()
37493722
- returns: <[string]> Browser websocket url.
@@ -3773,15 +3746,15 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.
37733746
- [browserType.errors](#browsertypeerrors)
37743747
- [browserType.executablePath()](#browsertypeexecutablepath)
37753748
- [browserType.launch([options])](#browsertypelaunchoptions)
3776-
- [browserType.launchPersistent(userDataDir, [options])](#browsertypelaunchpersistentuserdatadir-options)
3749+
- [browserType.launchPersistentContext(userDataDir, [options])](#browsertypelaunchpersistentcontextuserdatadir-options)
37773750
- [browserType.launchServer([options])](#browsertypelaunchserveroptions)
37783751
- [browserType.name()](#browsertypename)
37793752
<!-- GEN:stop -->
37803753

37813754
#### browserType.connect(options)
37823755
- `options` <[Object]>
3783-
- `wsEndpoint` <?[string]> A browser websocket endpoint to connect to.
3784-
- `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.
3756+
- `wsEndpoint` <[string]> A browser websocket endpoint to connect to.
3757+
- `slowMo` <?[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to 0.
37853758
- returns: <[Promise]<[Browser]>>
37863759

37873760
This methods attaches Playwright to an existing browser instance.
@@ -3842,9 +3815,9 @@ try {
38423815
#### browserType.launch([options])
38433816
- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
38443817
- `headless` <[boolean]> Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the `devtools` option is `true`.
3845-
- `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). **BEWARE**: Playwright is only [guaranteed to work](https://github.com/Microsoft/playwright/#q-why-doesnt-playwright-vxxx-work-with-chromium-vyyy) with the bundled Chromium, Firefox or WebKit, use at your own risk.
3818+
- `executablePath` <[string]> Path to a browser executable to run instead of the bundled one. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). Note that Playwright [only works](https://github.com/Microsoft/playwright/#q-why-doesnt-playwright-vxxx-work-with-chromium-vyyy) with the bundled Chromium, Firefox or WebKit, use at your own risk.
38463819
- `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).
3847-
- `ignoreDefaultArgs` <[boolean]|[Array]<[string]>> If `true`, then do not use [`browserType.defaultArgs()`](#browsertypedefaultargsoptions). If an array is given, then filter out the given default arguments. Dangerous option; use with care. Defaults to `false`.
3820+
- `ignoreDefaultArgs` <[boolean]|[Array]<[string]>> If `true`, Playwright does not pass its own configurations args and only uses the ones from `args`. If an array is given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`.
38483821
- `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`.
38493822
- `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`.
38503823
- `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`.
@@ -3871,7 +3844,7 @@ const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
38713844
>
38723845
> See [`this article`](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for a description of the differences between Chromium and Chrome. [`This article`](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md) describes some differences for Linux users.
38733846
3874-
#### browserType.launchPersistent(userDataDir, [options])
3847+
#### browserType.launchPersistentContext(userDataDir, [options])
38753848
- `userDataDir` <[string]> Path to a User Data Directory, which stores browser session data like cookies and local storage. More details for [Chromium](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options#User_Profile).
38763849
- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
38773850
- `headless` <[boolean]> Whether to run browser in headless mode. More details for [Chromium](https://developers.google.com/web/updates/2017/04/headless-chrome) and [Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode). Defaults to `true` unless the `devtools` option is `true`.
@@ -3887,7 +3860,7 @@ const browser = await chromium.launch({ // Or 'firefox' or 'webkit'.
38873860
- `devtools` <[boolean]> **Chromium-only** Whether to auto-open a Developer Tools panel for each tab. If this option is `true`, the `headless` option will be set `false`.
38883861
- returns: <[Promise]<[BrowserContext]>> Promise which resolves to the browser app instance.
38893862

3890-
Launches browser instance that uses persistent storage located at `userDataDir`. If `userDataDir` is not specified, temporary folder is created for the persistent storage. That folder is deleted when browser closes.
3863+
Launches browser instance that uses persistent storage located at `userDataDir`.
38913864

38923865
#### browserType.launchServer([options])
38933866
- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:
@@ -4223,7 +4196,7 @@ const { chromium } = require('playwright');
42234196
(async () => {
42244197
const pathToExtension = require('path').join(__dirname, 'my-extension');
42254198
const userDataDir = '/tmp/test-user-data-dir';
4226-
const browserContext = await chromium.launchPersistent(userDataDir,{
4199+
const browserContext = await chromium.launchPersistentContext(userDataDir,{
42274200
headless: false,
42284201
args: [
42294202
`--disable-extensions-except=${pathToExtension}`,

src/network.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ export class Response {
284284
return this._finishedPromise;
285285
}
286286

287-
buffer(): Promise<platform.BufferType> {
287+
body(): Promise<platform.BufferType> {
288288
if (!this._contentPromise) {
289289
this._contentPromise = this._finishedPromise.then(async error => {
290290
if (error)
@@ -296,7 +296,7 @@ export class Response {
296296
}
297297

298298
async text(): Promise<string> {
299-
const content = await this.buffer();
299+
const content = await this.body();
300300
return content.toString('utf8');
301301
}
302302

src/server/browserType.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ export interface BrowserType {
4747
name(): string;
4848
launch(options?: LaunchOptions & { slowMo?: number }): Promise<Browser>;
4949
launchServer(options?: LaunchOptions & { port?: number }): Promise<BrowserServer>;
50-
launchPersistent(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext>;
50+
launchPersistentContext(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext>;
5151
connect(options: ConnectOptions): Promise<Browser>;
5252
downloadBrowserIfNeeded(progress?: OnProgressCallback): Promise<void>;
5353
devices: types.Devices;

src/server/chromium.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export class Chromium implements BrowserType {
5353

5454
async launch(options?: LaunchOptions & { slowMo?: number }): Promise<CRBrowser> {
5555
if (options && (options as any).userDataDir)
56-
throw new Error('userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistent` instead');
56+
throw new Error('userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistentContext` instead');
5757
const { browserServer, transport } = await this._launchServer(options, 'local');
5858
const browser = await CRBrowser.connect(transport!, false, options && options.slowMo);
5959
(browser as any)['__server__'] = browserServer;
@@ -64,7 +64,7 @@ export class Chromium implements BrowserType {
6464
return (await this._launchServer(options, 'server', undefined, options && options.port)).browserServer;
6565
}
6666

67-
async launchPersistent(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext> {
67+
async launchPersistentContext(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext> {
6868
const { timeout = 30000 } = options || {};
6969
const { transport } = await this._launchServer(options, 'persistent', userDataDir);
7070
const browser = await CRBrowser.connect(transport!, true);

src/server/firefox.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ export class Firefox implements BrowserType {
6262

6363
async launch(options?: LaunchOptions & { slowMo?: number }): Promise<FFBrowser> {
6464
if (options && (options as any).userDataDir)
65-
throw new Error('userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistent` instead');
65+
throw new Error('userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistentContext` instead');
6666
const browserServer = await this._launchServer(options, 'local');
6767
const browser = await platform.connectToWebsocket(browserServer.wsEndpoint()!, transport => {
6868
return FFBrowser.connect(transport, false, options && options.slowMo);
@@ -77,7 +77,7 @@ export class Firefox implements BrowserType {
7777
return await this._launchServer(options, 'server', undefined, options && options.port);
7878
}
7979

80-
async launchPersistent(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext> {
80+
async launchPersistentContext(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext> {
8181
const { timeout = 30000 } = options || {};
8282
const browserServer = await this._launchServer(options, 'persistent', userDataDir);
8383
const browser = await platform.connectToWebsocket(browserServer.wsEndpoint()!, transport => {

src/server/webkit.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ export class WebKit implements BrowserType {
6565

6666
async launch(options?: LaunchOptions & { slowMo?: number }): Promise<WKBrowser> {
6767
if (options && (options as any).userDataDir)
68-
throw new Error('userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistent` instead');
68+
throw new Error('userDataDir option is not supported in `browserType.launch`. Use `browserType.launchPersistentContext` instead');
6969
const { browserServer, transport } = await this._launchServer(options, 'local');
7070
const browser = await WKBrowser.connect(transport!, options && options.slowMo);
7171
(browser as any)['__server__'] = browserServer;
@@ -76,7 +76,7 @@ export class WebKit implements BrowserType {
7676
return (await this._launchServer(options, 'server', undefined, options && options.port)).browserServer;
7777
}
7878

79-
async launchPersistent(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext> {
79+
async launchPersistentContext(userDataDir: string, options?: LaunchOptions): Promise<BrowserContext> {
8080
const { timeout = 30000 } = options || {};
8181
const { transport } = await this._launchServer(options, 'persistent', userDataDir);
8282
const browser = await WKBrowser.connect(transport!, undefined, true);

test/chromium/launcher.spec.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ module.exports.describe = function({testRunner, expect, defaultBrowserOptions, p
7979
describe('extensions', () => {
8080
it('should return background pages', async() => {
8181
const userDataDir = await makeUserDataDir();
82-
const context = await playwright.launchPersistent(userDataDir, extensionOptions);
82+
const context = await playwright.launchPersistentContext(userDataDir, extensionOptions);
8383
const backgroundPages = await context.backgroundPages();
8484
let backgroundPage = backgroundPages.length
8585
? backgroundPages[0]

test/defaultbrowsercontext.spec.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ module.exports.describe = function ({ testRunner, expect, defaultBrowserOptions,
2525
const {it, fit, xit, dit} = testRunner;
2626
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
2727

28-
describe('launchPersistent()', function() {
28+
describe('launchPersistentContext()', function() {
2929
beforeEach(async state => {
3030
state.userDataDir = await makeUserDataDir();
31-
state.browserContext = await playwright.launchPersistent(state.userDataDir, defaultBrowserOptions);
31+
state.browserContext = await playwright.launchPersistentContext(state.userDataDir, defaultBrowserOptions);
3232
state.page = await state.browserContext.newPage();
3333
});
3434
afterEach(async state => {

0 commit comments

Comments
 (0)