Skip to content

Commit

Permalink
feat(api): make browser.newPage own the context, brush up apis
Browse files Browse the repository at this point in the history
  • Loading branch information
pavelfeldman committed Feb 8, 2020
1 parent e9c1477 commit 86868b4
Show file tree
Hide file tree
Showing 23 changed files with 138 additions and 123 deletions.
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ const playwright = require('playwright');
(async () => {
for (const browserType of ['chromium', 'firefox', 'webkit']) {
const browser = await playwright[browserType].launch();
const page = await browser.newPage('http://whatsmyuseragent.org/');
const page = await browser.newPage();
await page.goto('http://whatsmyuseragent.org/');
await page.screenshot({ path: `example-${browserType}.png` });
await browser.close();
}
Expand All @@ -57,13 +58,14 @@ const iPhone11 = devices['iPhone 11 Pro'];

(async () => {
const browser = await webkit.launch();
const page = await browser.newPage('https://maps.google.com', {
const page = await browser.newPage({
viewport: iPhone11.viewport,
userAgent: iPhone11.userAgent,
geolocation: { longitude: 12.492507, latitude: 41.889938 },
permissions: { 'https://www.google.com': ['geolocation'] }
});

await page.goto('https://maps.google.com');
await page.click('text="Your location"');
await page.waitForRequest(/.*preview\/pwa/);
await page.screenshot({ path: 'colosseum-iphone.png' });
Expand All @@ -79,12 +81,13 @@ const pixel2 = devices['Pixel 2'];

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage('https://maps.google.com', {
const page = await browser.newPage({
viewport: pixel2.viewport,
userAgent: pixel2.userAgent,
geolocation: { longitude: 12.492507, latitude: 41.889938 },
permissions: { 'https://www.google.com': ['geolocation'] }
});
await page.goto('https://maps.google.com');
await page.click('text="Your location"');
await page.waitForRequest(/.*pwa\/net.js.*/);
await page.screenshot({ path: 'colosseum-android.png' });
Expand All @@ -101,7 +104,8 @@ const { firefox } = require('playwright');

(async () => {
const browser = await firefox.launch();
const page = await browser.newPage('https://www.example.com/');
const page = await browser.newPage();
await page.goto('https://www.example.com/');
const dimensions = await page.evaluate(() => {
return {
width: document.documentElement.clientWidth,
Expand Down
91 changes: 50 additions & 41 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ const { chromium, firefox, webkit } = require('playwright');

(async () => {
const browser = await chromium.launch(); // Or 'firefox' or 'webkit'.
const page = await browser.newPage('http://example.com');
const page = await browser.newPage();
await page.goto('http://example.com');
// other actions...
await browser.close();
})();
Expand Down Expand Up @@ -81,7 +82,8 @@ const iPhone = devices['iPhone 6'];
viewport: iPhone.viewport,
userAgent: iPhone.userAgent
});
const page = await context.newPage('http://example.com');
const page = await context.newPage();
await page.goto('http://example.com');
// other actions...
await browser.close();
})();
Expand Down Expand Up @@ -136,7 +138,8 @@ const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.

(async () => {
const browser = await firefox.launch();
const page = await browser.newPage('https://example.com');
const page = await browser.newPage();
await page.goto('https://example.com');
await browser.close();
})();
```
Expand All @@ -145,11 +148,11 @@ See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific

<!-- GEN:toc -->
- [event: 'disconnected'](#event-disconnected)
- [browser.browserContexts()](#browserbrowsercontexts)
- [browser.close()](#browserclose)
- [browser.contexts()](#browsercontexts)
- [browser.isConnected()](#browserisconnected)
- [browser.newContext(options)](#browsernewcontextoptions)
- [browser.newPage(url, [options])](#browsernewpageurl-options)
- [browser.newPage([options])](#browsernewpageoptions)
- [browser.pages()](#browserpages)
<!-- GEN:stop -->

Expand All @@ -158,12 +161,6 @@ Emitted when Browser gets disconnected from the browser application. This might
- Browser application is closed or crashed.
- The [`browser.disconnect`](#browserdisconnect) method was called.

#### browser.browserContexts()
- returns: <[Array]<[BrowserContext]>>

Returns an array of all open browser contexts. In a newly created browser, this will return
a single instance of [BrowserContext].

#### browser.close()
- returns: <[Promise]>

Expand All @@ -173,6 +170,12 @@ In case this browser is obtained using [browserType.connect](#browsertypeconnect

The [Browser] object itself is considered to be disposed and cannot be used anymore.

#### browser.contexts()
- returns: <[Array]<[BrowserContext]>>

Returns an array of all open browser contexts. In a newly created browser, this will return
a single instance of [BrowserContext].

#### browser.isConnected()

- returns: <[boolean]>
Expand Down Expand Up @@ -206,12 +209,12 @@ Creates a new browser context. It won't share cookies/cache with other browser c
// Create a new incognito browser context.
const context = await browser.newContext();
// Create a new page in a pristine context.
const page = await context.newPage('https://example.com');
const page = await context.newPage();
await page.goto('https://example.com');
})();
```

#### browser.newPage(url, [options])
- `url` <?[string]> Optional url to navigate the page to.
#### browser.newPage([options])
- `options` <[Object]>
- `ignoreHTTPSErrors` <?[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`.
- `bypassCSP` <?[boolean]> Toggles bypassing page's Content-Security-Policy.
Expand All @@ -230,7 +233,7 @@ Creates a new browser context. It won't share cookies/cache with other browser c
- `permissions` <[Object]> A map from origin keys to permissions values. See [browserContext.setPermissions](#browsercontextsetpermissionsorigin-permissions) for more details.
- returns: <[Promise]<[Page]>>

Creates a new page in a new browser context and optionally navigates it to the specified URL.
Creates a new page in a new browser context. The context is created for this page, links and popups opened from this page. When this page is closed, its context is closed along with all the pages it contains.

#### browser.pages()
- returns: <[Promise]<[Array]<[Page]>>> Promise which resolves to an array of all open pages.
Expand All @@ -253,7 +256,8 @@ Playwright allows creation of "incognito" browser contexts with `browser.newCont
// Create a new incognito browser context
const context = await browser.newContext();
// Create a new page inside context.
const page = await context.newPage('https://example.com');
const page = await context.newPage();
await page.goto('https://example.com');
// Dispose context once it's no longer needed.
await context.close();
```
Expand All @@ -263,7 +267,7 @@ await context.close();
- [browserContext.clearPermissions()](#browsercontextclearpermissions)
- [browserContext.close()](#browsercontextclose)
- [browserContext.cookies([...urls])](#browsercontextcookiesurls)
- [browserContext.newPage(url)](#browsercontextnewpageurl)
- [browserContext.newPage()](#browsercontextnewpage)
- [browserContext.pages()](#browsercontextpages)
- [browserContext.setCookies(cookies)](#browsercontextsetcookiescookies)
- [browserContext.setGeolocation(geolocation)](#browsercontextsetgeolocationgeolocation)
Expand Down Expand Up @@ -314,11 +318,10 @@ If URLs are specified, only cookies that affect those URLs are returned.

> **NOTE** the default browser context cannot be closed.
#### browserContext.newPage(url)
- `url` <?[string]> Optional url to navigate the page to.
#### browserContext.newPage()
- returns: <[Promise]<[Page]>>

Creates a new page in the browser context and optionally navigates it to the specified URL.
Creates a new page in the browser context.

#### browserContext.pages()
- returns: <[Promise]<[Array]<[Page]>>> Promise which resolves to an array of all open pages. Non visible pages, such as `"background_page"`, will not be listed here. You can find them using [target.page()](#targetpage).
Expand Down Expand Up @@ -397,7 +400,8 @@ const { webkit } = require('playwright'); // Or 'chromium' or 'firefox'.
(async () => {
const browser = await webkit.launch();
const context = await browser.newContext();
const page = await context.newPage('https://example.com');
const page = await context.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'screenshot.png'});
await browser.close();
})();
Expand Down Expand Up @@ -449,11 +453,11 @@ page.removeListener('request', logRequest);
- [page.addScriptTag(options)](#pageaddscripttagoptions)
- [page.addStyleTag(options)](#pageaddstyletagoptions)
- [page.authenticate(credentials)](#pageauthenticatecredentials)
- [page.browserContext()](#pagebrowsercontext)
- [page.check(selector, [options])](#pagecheckselector-options)
- [page.click(selector[, options])](#pageclickselector-options)
- [page.close([options])](#pagecloseoptions)
- [page.content()](#pagecontent)
- [page.context()](#pagecontext)
- [page.coverage](#pagecoverage)
- [page.dblclick(selector[, options])](#pagedblclickselector-options)
- [page.emulateMedia(options)](#pageemulatemediaoptions)
Expand Down Expand Up @@ -729,12 +733,6 @@ Provide credentials for [HTTP authentication](https://developer.mozilla.org/en-U

To disable authentication, pass `null`.

#### page.browserContext()

- returns: <[BrowserContext]>

Get the browser context that the page belongs to.

#### page.check(selector, [options])
- `selector` <[string]> A selector to search for checkbox or radio button to check. If there are multiple elements satisfying the selector, the first will be checked.
- `options` <[Object]>
Expand Down Expand Up @@ -792,6 +790,12 @@ By default, `page.close()` **does not** run beforeunload handlers.

Gets the full HTML contents of the page, including the doctype.

#### page.context()

- returns: <[BrowserContext]>

Get the browser context that the page belongs to.

#### page.coverage

- returns: <[Coverage]>
Expand Down Expand Up @@ -1633,7 +1637,8 @@ const { firefox } = require('playwright'); // Or 'chromium' or 'webkit'.

(async () => {
const browser = await firefox.launch();
const page = await browser.newPage('https://www.google.com/chrome/browser/canary.html');
const page = await browser.newPage();
await page.goto('https://www.google.com/chrome/browser/canary.html');
dumpFrameTree(page.mainFrame(), '');
await browser.close();

Expand Down Expand Up @@ -2224,7 +2229,8 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage('https://example.com');
const page = await browser.newPage();
await page.goto('https://example.com');
const hrefElement = await page.$('a');
await hrefElement.click();
// ...
Expand Down Expand Up @@ -3143,7 +3149,8 @@ const { selectors, firefox } = require('playwright'); // Or 'chromium' or 'webk
await selectors.register(createTagNameEngine);

const browser = await firefox.launch();
const page = await browser.newPage('http://example.com');
const page = await browser.newPage();
await page.goto('https://example.com');

// Use the selector prefixed with its name.
const button = await page.$('tag=button');
Expand Down Expand Up @@ -3453,7 +3460,8 @@ const { chromium } = require('playwright'); // Or 'firefox' or 'webkit'.

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage('http://example.com');
const page = await browser.newPage();
await page.goto('https://example.com');
// other actions...
await browser.close();
})();
Expand Down Expand Up @@ -3493,7 +3501,8 @@ const iPhone = webkit.devices['iPhone 6'];
viewport: iPhone.viewport,
userAgent: iPhone.userAgent
});
const page = await context.newPage('http://example.com');
const page = await context.newPage();
await page.goto('https://example.com');
// other actions...
await browser.close();
})();
Expand Down Expand Up @@ -3638,11 +3647,11 @@ await browser.stopTracing();
<!-- GEN:stop -->
<!-- GEN:toc-extends-Browser -->
- [event: 'disconnected'](#event-disconnected)
- [browser.browserContexts()](#browserbrowsercontexts)
- [browser.close()](#browserclose)
- [browser.contexts()](#browsercontexts)
- [browser.isConnected()](#browserisconnected)
- [browser.newContext(options)](#browsernewcontextoptions)
- [browser.newPage(url, [options])](#browsernewpageurl-options)
- [browser.newPage([options])](#browsernewpageoptions)
- [browser.pages()](#browserpages)
<!-- GEN:stop -->

Expand Down Expand Up @@ -3760,15 +3769,15 @@ to send messages.


<!-- GEN:toc -->
- [chromiumTarget.browserContext()](#chromiumtargetbrowsercontext)
- [chromiumTarget.context()](#chromiumtargetcontext)
- [chromiumTarget.createCDPSession()](#chromiumtargetcreatecdpsession)
- [chromiumTarget.opener()](#chromiumtargetopener)
- [chromiumTarget.page()](#chromiumtargetpage)
- [chromiumTarget.type()](#chromiumtargettype)
- [chromiumTarget.url()](#chromiumtargeturl)
<!-- GEN:stop -->

#### chromiumTarget.browserContext()
#### chromiumTarget.context()

- returns: <[BrowserContext]>

Expand Down Expand Up @@ -3805,11 +3814,11 @@ Firefox browser instance does not expose Firefox-specific features.

<!-- GEN:toc-extends-Browser -->
- [event: 'disconnected'](#event-disconnected)
- [browser.browserContexts()](#browserbrowsercontexts)
- [browser.close()](#browserclose)
- [browser.contexts()](#browsercontexts)
- [browser.isConnected()](#browserisconnected)
- [browser.newContext(options)](#browsernewcontextoptions)
- [browser.newPage(url, [options])](#browsernewpageurl-options)
- [browser.newPage([options])](#browsernewpageoptions)
- [browser.pages()](#browserpages)
<!-- GEN:stop -->

Expand All @@ -3821,11 +3830,11 @@ WebKit browser instance does not expose WebKit-specific features.

<!-- GEN:toc-extends-Browser -->
- [event: 'disconnected'](#event-disconnected)
- [browser.browserContexts()](#browserbrowsercontexts)
- [browser.close()](#browserclose)
- [browser.contexts()](#browsercontexts)
- [browser.isConnected()](#browserisconnected)
- [browser.newContext(options)](#browsernewcontextoptions)
- [browser.newPage(url, [options])](#browsernewpageurl-options)
- [browser.newPage([options])](#browsernewpageoptions)
- [browser.pages()](#browserpages)
<!-- GEN:stop -->

Expand Down
13 changes: 10 additions & 3 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ import { Page } from './page';

export interface Browser extends platform.EventEmitterType {
newContext(options?: BrowserContextOptions): Promise<BrowserContext>;
browserContexts(): BrowserContext[];
contexts(): BrowserContext[];
pages(): Promise<Page[]>;
newPage(url?: string, options?: BrowserContextOptions): Promise<Page>;
newPage(options?: BrowserContextOptions): Promise<Page>;
isConnected(): boolean;
close(): Promise<void>;
}
Expand All @@ -34,12 +34,19 @@ export type ConnectOptions = {

export async function collectPages(browser: Browser): Promise<Page[]> {
const result: Promise<Page[]>[] = [];
for (const browserContext of browser.browserContexts())
for (const browserContext of browser.contexts())
result.push(browserContext.pages());
const pages: Page[] = [];
for (const group of await Promise.all(result))
pages.push(...group);
return pages;
}

export async function createContextWithPage(browser: Browser, options?: BrowserContextOptions): Promise<Page> {
const browserContext = await browser.newContext(options);
const page = await browserContext.newPage();
page._ownedContext = browserContext;
return page;
}

export type LaunchType = 'local' | 'server' | 'persistent';
7 changes: 2 additions & 5 deletions src/browserContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,8 @@ export class BrowserContext {
return this._delegate.pages();
}

async newPage(url?: string): Promise<Page> {
const page = await this._delegate.newPage();
if (url)
await page.goto(url);
return page;
async newPage(): Promise<Page> {
return this._delegate.newPage();
}

async cookies(...urls: string[]): Promise<network.NetworkCookie[]> {
Expand Down
Loading

0 comments on commit 86868b4

Please sign in to comment.