Skip to content

Commit

Permalink
api: introduce Browser.version() (microsoft#3177)
Browse files Browse the repository at this point in the history
  • Loading branch information
dgozman authored Jul 27, 2020
1 parent e406119 commit 97c1000
Show file tree
Hide file tree
Showing 10 changed files with 55 additions and 2 deletions.
10 changes: 10 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ See [ChromiumBrowser], [FirefoxBrowser] and [WebKitBrowser] for browser-specific
- [browser.isConnected()](#browserisconnected)
- [browser.newContext([options])](#browsernewcontextoptions)
- [browser.newPage([options])](#browsernewpageoptions)
- [browser.version()](#browserversion)
<!-- GEN:stop -->

#### event: 'disconnected'
Expand Down Expand Up @@ -266,6 +267,12 @@ Creates a new page in a new browser context. Closing this page will close the co

This is a convenience API that should only be used for the single-page scenarios and short snippets. Production code and testing frameworks should explicitly create [browser.newContext](#browsernewcontextoptions) followed by the [browserContext.newPage](#browsercontextnewpage) to control their exact life times.

#### browser.version()

- returns: <[string]>

Returns the browser version.

### class: BrowserContext

* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)
Expand Down Expand Up @@ -4180,6 +4187,7 @@ await browser.stopTracing();
- [browser.isConnected()](#browserisconnected)
- [browser.newContext([options])](#browsernewcontextoptions)
- [browser.newPage([options])](#browsernewpageoptions)
- [browser.version()](#browserversion)
<!-- GEN:stop -->

#### chromiumBrowser.newBrowserCDPSession()
Expand Down Expand Up @@ -4387,6 +4395,7 @@ Firefox browser instance does not expose Firefox-specific features.
- [browser.isConnected()](#browserisconnected)
- [browser.newContext([options])](#browsernewcontextoptions)
- [browser.newPage([options])](#browsernewpageoptions)
- [browser.version()](#browserversion)
<!-- GEN:stop -->

### class: WebKitBrowser
Expand All @@ -4402,6 +4411,7 @@ WebKit browser instance does not expose WebKit-specific features.
- [browser.isConnected()](#browserisconnected)
- [browser.newContext([options])](#browsernewcontextoptions)
- [browser.newPage([options])](#browsernewpageoptions)
- [browser.version()](#browserversion)
<!-- GEN:stop -->

### Environment Variables
Expand Down
2 changes: 2 additions & 0 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export interface Browser extends EventEmitter {
newPage(options?: BrowserContextOptions): Promise<Page>;
isConnected(): boolean;
close(): Promise<void>;
version(): string;
}

export abstract class BrowserBase extends EventEmitter implements Browser {
Expand All @@ -61,6 +62,7 @@ export abstract class BrowserBase extends EventEmitter implements Browser {
abstract contexts(): BrowserContext[];
abstract isConnected(): boolean;
abstract _disconnect(): void;
abstract version(): string;

async newPage(options?: BrowserContextOptions): Promise<Page> {
const context = await this.newContext(options);
Expand Down
6 changes: 6 additions & 0 deletions src/chromium/crBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export class CRBrowser extends BrowserBase {
_serviceWorkers = new Map<string, CRServiceWorker>();
_devtools?: CRDevTools;
_isMac = false;
private _version = '';

private _tracingRecording = false;
private _tracingPath: string | null = '';
Expand All @@ -53,6 +54,7 @@ export class CRBrowser extends BrowserBase {
const session = connection.rootSession;
const version = await session.send('Browser.getVersion');
browser._isMac = version.userAgent.includes('Macintosh');
browser._version = version.product.substring(version.product.indexOf('/') + 1);
if (!options.persistent) {
await session.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
return browser;
Expand Down Expand Up @@ -110,6 +112,10 @@ export class CRBrowser extends BrowserBase {
return Array.from(this._contexts.values());
}

version(): string {
return this._version;
}

_onAttachedToTarget({targetInfo, sessionId, waitingForDebugger}: Protocol.Target.attachedToTargetPayload) {
if (targetInfo.type === 'browser')
return;
Expand Down
11 changes: 11 additions & 0 deletions src/firefox/ffBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,14 @@ export class FFBrowser extends BrowserBase {
readonly _ffPages: Map<string, FFPage>;
readonly _contexts: Map<string, FFBrowserContext>;
private _eventListeners: RegisteredListener[];
private _version = '';

static async connect(transport: ConnectionTransport, options: BrowserOptions): Promise<FFBrowser> {
const connection = new FFConnection(SlowMoTransport.wrap(transport, options.slowMo), options.loggers);
const browser = new FFBrowser(connection, options);
const promises: Promise<any>[] = [
connection.send('Browser.enable', { attachToDefaultContext: !!options.persistent }),
browser._initVersion(),
];
if (options.persistent) {
browser._defaultContext = new FFBrowserContext(browser, null, options.persistent);
Expand All @@ -62,6 +64,11 @@ export class FFBrowser extends BrowserBase {
];
}

async _initVersion() {
const result = await this._connection.send('Browser.getInfo');
this._version = result.version.substring(result.version.indexOf('/') + 1);
}

isConnected(): boolean {
return !this._connection._closed;
}
Expand All @@ -81,6 +88,10 @@ export class FFBrowser extends BrowserBase {
return Array.from(this._contexts.values());
}

version(): string {
return this._version;
}

_onDetachedFromTarget(payload: Protocol.Browser.detachedFromTargetPayload) {
const ffPage = this._ffPages.get(payload.targetId)!;
this._ffPages.delete(payload.targetId);
Expand Down
4 changes: 3 additions & 1 deletion src/rpc/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,9 @@ export type BrowserServerKillParams = {};
export type BrowserServerKillResult = void;

// ----------- Browser -----------
export type BrowserInitializer = {};
export type BrowserInitializer = {
version: string,
};
export interface BrowserChannel extends Channel {
on(event: 'close', callback: (params: BrowserCloseEvent) => void): this;
close(params?: BrowserCloseParams): Promise<BrowserCloseResult>;
Expand Down
4 changes: 4 additions & 0 deletions src/rpc/client/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ export class Browser extends ChannelOwner<BrowserChannel, BrowserInitializer> {
return [...this._contexts];
}

version(): string {
return this._initializer.version;
}

async newPage(options: types.BrowserContextOptions & { logger?: LoggerSink } = {}): Promise<Page> {
const context = await this.newContext(options);
const page = await context.newPage();
Expand Down
3 changes: 3 additions & 0 deletions src/rpc/protocol.yml
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,9 @@ BrowserServer:
Browser:
type: interface

initializer:
version: string

commands:

close:
Expand Down
2 changes: 1 addition & 1 deletion src/rpc/server/browserDispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { headersArrayToObject } from '../serializers';

export class BrowserDispatcher extends Dispatcher<Browser, BrowserInitializer> implements BrowserChannel {
constructor(scope: DispatcherScope, browser: BrowserBase) {
super(scope, browser, 'Browser', {}, true);
super(scope, browser, 'Browser', { version: browser.version() }, true);
browser.on(Events.Browser.Disconnected, () => {
this._dispatchEvent('close');
this._dispose();
Expand Down
5 changes: 5 additions & 0 deletions src/webkit/wkBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { kPageProxyMessageReceived, PageProxyMessageReceivedPayload, WKConnectio
import { WKPage } from './wkPage';

const DEFAULT_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15';
const BROWSER_VERSION = '14.0';

export class WKBrowser extends BrowserBase {
private readonly _connection: WKConnection;
Expand Down Expand Up @@ -85,6 +86,10 @@ export class WKBrowser extends BrowserBase {
return Array.from(this._contexts.values());
}

version(): string {
return BROWSER_VERSION;
}

_onDownloadCreated(payload: Protocol.Playwright.downloadCreatedPayload) {
const page = this._wkPages.get(payload.pageProxyId);
if (!page)
Expand Down
10 changes: 10 additions & 0 deletions test/browser.jest.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,13 @@ describe('Browser.newPage', function() {
expect(error.message).toContain('Please use browser.newContext()');
});
});

describe('Browser.version', function() {
it('should work', async function({browser}) {
const version = browser.version();
if (CHROMIUM)
expect(version.match(/^\d+\.\d+\.\d+\.\d+$/)).toBeTruthy();
else
expect(version.match(/^\d+\.\d+$/)).toBeTruthy();
});
});

0 comments on commit 97c1000

Please sign in to comment.