Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: allow launchServer with a sharedBrowser (#36054)
Dmitry Gozman928dee489672
diff --git a/packages/playwright-core/src/browserServerImpl.ts b/packages/playwright-core/src/browserServerImpl.tsindex 47ab0f5dcf..d8bcda0e79 100644--- a/packages/playwright-core/src/browserServerImpl.ts+++ b/packages/playwright-core/src/browserServerImpl.ts@@ -36,7 +36,7 @@ export class BrowserServerLauncherImpl implements BrowserServerLauncher {this._browserName = browserName;}- async launchServer(options: LaunchServerOptions = {}): Promise<BrowserServer> {+ async launchServer(options: LaunchServerOptions & { _sharedBrowser?: boolean } = {}): Promise<BrowserServer> {const playwright = createPlaywright({ sdkLanguage: 'javascript', isServer: true });// TODO: enable socks proxy once ipv6 is supported.const socksProxy = false ? new SocksProxy() : undefined;@@ -59,7 +59,7 @@ export class BrowserServerLauncherImpl implements BrowserServerLauncher {const path = options.wsPath ? (options.wsPath.startsWith('/') ? options.wsPath : `/${options.wsPath}`) : `/${createGuid()}`;// 2. Start the server- const server = new PlaywrightServer({ mode: 'launchServer', path, maxConnections: Infinity, preLaunchedBrowser: browser, preLaunchedSocksProxy: socksProxy });+ const server = new PlaywrightServer({ mode: options._sharedBrowser ? 'launchServerShared' : 'launchServer', path, maxConnections: Infinity, preLaunchedBrowser: browser, preLaunchedSocksProxy: socksProxy });const wsEndpoint = await server.listen(options.port, options.host);// 3. Return the BrowserServer interfacediff --git a/packages/playwright-core/src/client/types.ts b/packages/playwright-core/src/client/types.tsindex acfbcbe056..193903fb80 100644--- a/packages/playwright-core/src/client/types.ts+++ b/packages/playwright-core/src/client/types.ts@@ -105,31 +105,10 @@ export type ConnectOptions = {timeout?: number,logger?: Logger,};-export type LaunchServerOptions = {- channel?: channels.BrowserTypeLaunchOptions['channel'],- executablePath?: string,- args?: string[],- ignoreDefaultArgs?: boolean | string[],- handleSIGINT?: boolean,- handleSIGTERM?: boolean,- handleSIGHUP?: boolean,- timeout?: number,- env?: Env,- headless?: boolean,- devtools?: boolean,- proxy?: {- server: string,- bypass?: string,- username?: string,- password?: string- },- downloadsPath?: string,- chromiumSandbox?: boolean,+export type LaunchServerOptions = LaunchOptions & {host?: string,port?: number,wsPath?: string,- logger?: Logger,- firefoxUserPrefs?: { [key: string]: string | number | boolean };};export type LaunchAndroidServerOptions = {diff --git a/packages/playwright-core/src/remote/playwrightConnection.ts b/packages/playwright-core/src/remote/playwrightConnection.tsindex af033dbbbe..2f9abfbf01 100644--- a/packages/playwright-core/src/remote/playwrightConnection.ts+++ b/packages/playwright-core/src/remote/playwrightConnection.ts@@ -38,6 +38,7 @@ type Options = {socksProxyPattern: string | undefined,browserName: string | null,launchOptions: LaunchOptions,+ sharedBrowser?: boolean,};type PreLaunched = {@@ -138,7 +139,7 @@ export class PlaywrightConnection {this.close({ code: 1001, reason: 'Browser closed' });});- return new PlaywrightDispatcher(scope, playwright, ownedSocksProxy, browser);+ return new PlaywrightDispatcher(scope, playwright, { socksProxy: ownedSocksProxy, preLaunchedBrowser: browser });}private async _initPreLaunchedBrowserMode(scope: RootDispatcher) {@@ -154,7 +155,11 @@ export class PlaywrightConnection {this.close({ code: 1001, reason: 'Browser closed' });});- const playwrightDispatcher = new PlaywrightDispatcher(scope, playwright, this._preLaunched.socksProxy, browser);+ const playwrightDispatcher = new PlaywrightDispatcher(scope, playwright, {+ socksProxy: this._preLaunched.socksProxy,+ preLaunchedBrowser: browser,+ sharedBrowser: this._options.sharedBrowser,+ });// In pre-launched mode, keep only the pre-launched browser.for (const b of playwright.allBrowsers()) {if (b !== browser)@@ -172,7 +177,7 @@ export class PlaywrightConnection {// Underlying browser did close for some reason - force disconnect the client.this.close({ code: 1001, reason: 'Android device disconnected' });});- const playwrightDispatcher = new PlaywrightDispatcher(scope, playwright, undefined, undefined, androidDevice);+ const playwrightDispatcher = new PlaywrightDispatcher(scope, playwright, { preLaunchedAndroidDevice: androidDevice });this._cleanups.push(() => playwrightDispatcher.cleanup());return playwrightDispatcher;}@@ -233,7 +238,7 @@ export class PlaywrightConnection {}});- const playwrightDispatcher = new PlaywrightDispatcher(scope, playwright, undefined, browser);+ const playwrightDispatcher = new PlaywrightDispatcher(scope, playwright, { preLaunchedBrowser: browser });return playwrightDispatcher;}diff --git a/packages/playwright-core/src/remote/playwrightServer.ts b/packages/playwright-core/src/remote/playwrightServer.tsindex 73ed85c2ce..9a564c4252 100644--- a/packages/playwright-core/src/remote/playwrightServer.ts+++ b/packages/playwright-core/src/remote/playwrightServer.ts@@ -34,7 +34,7 @@ import type { LaunchOptions } from '../server/types';type ServerOptions = {path: string;maxConnections: number;- mode: 'default' | 'launchServer' | 'extension';+ mode: 'default' | 'launchServer' | 'launchServerShared' | 'extension';preLaunchedBrowser?: Browser;preLaunchedAndroidDevice?: AndroidDevice;preLaunchedSocksProxy?: SocksProxy;@@ -98,7 +98,7 @@ export class PlaywrightServer {} else if (isExtension) {clientType = 'reuse-browser';semaphore = reuseBrowserSemaphore;- } else if (this._options.mode === 'launchServer') {+ } else if (this._options.mode === 'launchServer' || this._options.mode === 'launchServerShared') {clientType = 'pre-launched-browser-or-android';semaphore = browserSemaphore;}@@ -106,7 +106,13 @@ export class PlaywrightServer {return new PlaywrightConnection(semaphore.acquire(),clientType, ws,- { socksProxyPattern: proxyValue, browserName, launchOptions, allowFSPaths: this._options.mode === 'extension' },+ {+ socksProxyPattern: proxyValue,+ browserName,+ launchOptions,+ allowFSPaths: this._options.mode === 'extension',+ sharedBrowser: this._options.mode === 'launchServerShared',+ },{playwright: this._preLaunchedPlaywright,browser: this._options.preLaunchedBrowser,diff --git a/packages/playwright-core/src/server/dispatchers/browserDispatcher.ts b/packages/playwright-core/src/server/dispatchers/browserDispatcher.tsindex bf822ce863..186ec73faa 100644--- a/packages/playwright-core/src/server/dispatchers/browserDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/browserDispatcher.ts@@ -22,23 +22,35 @@ import { BrowserContext } from '../browserContext';import { ArtifactDispatcher } from './artifactDispatcher';import type { BrowserTypeDispatcher } from './browserTypeDispatcher';-import type { RootDispatcher } from './dispatcher';import type { PageDispatcher } from './pageDispatcher';import type { CRBrowser } from '../chromium/crBrowser';import type { CallMetadata } from '../instrumentation';import type * as channels from '@protocol/channels';+type BrowserDispatcherOptions = {+ // Do not allow to close this browser.+ ignoreStopAndKill?: boolean,+ // Only expose browser contexts created by this dispatcher. By default, all contexts are exposed.+ isolateContexts?: boolean,+};+export class BrowserDispatcher extends Dispatcher<Browser, channels.BrowserChannel, BrowserTypeDispatcher> implements channels.BrowserChannel {_type_Browser = true;+ private _options: BrowserDispatcherOptions;+ private _isolatedContexts = new Set<BrowserContext>();- constructor(scope: BrowserTypeDispatcher, browser: Browser) {+ constructor(scope: BrowserTypeDispatcher, browser: Browser, options: BrowserDispatcherOptions = {}) {super(scope, browser, 'Browser', { version: browser.version(), name: browser.options.name });- this.addObjectListener(Browser.Events.Context, (context: BrowserContext) => this._dispatchEvent('context', { context: BrowserContextDispatcher.from(this, context) }));- this.addObjectListener(Browser.Events.Disconnected, () => this._didClose());- if (browser._defaultContext)- this._dispatchEvent('context', { context: BrowserContextDispatcher.from(this, browser._defaultContext) });- for (const context of browser.contexts())- this._dispatchEvent('context', { context: BrowserContextDispatcher.from(this, context) });+ this._options = options;++ if (!options.isolateContexts) {+ this.addObjectListener(Browser.Events.Context, (context: BrowserContext) => this._dispatchEvent('context', { context: BrowserContextDispatcher.from(this, context) }));+ this.addObjectListener(Browser.Events.Disconnected, () => this._didClose());+ if (browser._defaultContext)+ this._dispatchEvent('context', { context: BrowserContextDispatcher.from(this, browser._defaultContext) });+ for (const context of browser.contexts())+ this._dispatchEvent('context', { context: BrowserContextDispatcher.from(this, context) });+ }}_didClose() {@@ -47,12 +59,33 @@ export class BrowserDispatcher extends Dispatcher<Browser, channels.BrowserChann}async newContext(params: channels.BrowserNewContextParams, metadata: CallMetadata): Promise<channels.BrowserNewContextResult> {+ if (!this._options.isolateContexts) {+ const context = await this._object.newContext(metadata, params);+ const contextDispatcher = BrowserContextDispatcher.from(this, context);+ return { context: contextDispatcher };+ }++ if (params.recordVideo)+ params.recordVideo.dir = this._object.options.artifactsDir;const context = await this._object.newContext(metadata, params);- return { context: BrowserContextDispatcher.from(this, context) };+ this._isolatedContexts.add(context);+ context.on(BrowserContext.Events.Close, () => this._isolatedContexts.delete(context));+ const contextDispatcher = BrowserContextDispatcher.from(this, context);+ this._dispatchEvent('context', { context: contextDispatcher });+ return { context: contextDispatcher };}async newContextForReuse(params: channels.BrowserNewContextForReuseParams, metadata: CallMetadata): Promise<channels.BrowserNewContextForReuseResult> {- return await newContextForReuse(this._object, this, params, metadata);+ const { context, needsReset } = await this._object.newContextForReuse(params, metadata);+ if (needsReset) {+ const oldContextDispatcher = this.connection.existingDispatcher<BrowserContextDispatcher>(context);+ if (oldContextDispatcher)+ oldContextDispatcher._dispose();+ await context.resetForReuse(metadata, params);+ }+ const contextDispatcher = BrowserContextDispatcher.from(this, context);+ this._dispatchEvent('context', { context: contextDispatcher });+ return { context: contextDispatcher };}async stopPendingOperations(params: channels.BrowserStopPendingOperationsParams, metadata: CallMetadata): Promise<channels.BrowserStopPendingOperationsResult> {@@ -60,11 +93,15 @@ export class BrowserDispatcher extends Dispatcher<Browser, channels.BrowserChann}async close(params: channels.BrowserCloseParams, metadata: CallMetadata): Promise<void> {+ if (this._options.ignoreStopAndKill)+ return;metadata.potentiallyClosesScope = true;await this._object.close(params);}async killForTests(_: any, metadata: CallMetadata): Promise<void> {+ if (this._options.ignoreStopAndKill)+ return;metadata.potentiallyClosesScope = true;await this._object.killForTests();}@@ -93,83 +130,8 @@ export class BrowserDispatcher extends Dispatcher<Browser, channels.BrowserChannconst crBrowser = this._object as CRBrowser;return { artifact: ArtifactDispatcher.from(this, await crBrowser.stopTracing()) };}-}--// This class implements multiplexing browser dispatchers over a single Browser instance.-export class ConnectedBrowserDispatcher extends Dispatcher<Browser, channels.BrowserChannel, RootDispatcher> implements channels.BrowserChannel {- _type_Browser = true;- private _contexts = new Set<BrowserContext>();-- constructor(scope: RootDispatcher, browser: Browser) {- super(scope, browser, 'Browser', { version: browser.version(), name: browser.options.name });- }-- async newContext(params: channels.BrowserNewContextParams, metadata: CallMetadata): Promise<channels.BrowserNewContextResult> {- if (params.recordVideo)- params.recordVideo.dir = this._object.options.artifactsDir;- const context = await this._object.newContext(metadata, params);- this._contexts.add(context);- context.on(BrowserContext.Events.Close, () => this._contexts.delete(context));- const contextDispatcher = BrowserContextDispatcher.from(this, context);- this._dispatchEvent('context', { context: contextDispatcher });- return { context: contextDispatcher };- }-- async newContextForReuse(params: channels.BrowserNewContextForReuseParams, metadata: CallMetadata): Promise<channels.BrowserNewContextForReuseResult> {- return await newContextForReuse(this._object, this as any as BrowserDispatcher, params, metadata);- }-- async stopPendingOperations(params: channels.BrowserStopPendingOperationsParams, metadata: CallMetadata): Promise<channels.BrowserStopPendingOperationsResult> {- await this._object.stopPendingOperations(params.reason);- }-- async close(): Promise<void> {- // Client should not send us Browser.close.- }-- async killForTests(): Promise<void> {- // Client should not send us Browser.killForTests.- }-- async defaultUserAgentForTest(): Promise<channels.BrowserDefaultUserAgentForTestResult> {- throw new Error('Client should not send us Browser.defaultUserAgentForTest');- }-- async newBrowserCDPSession(): Promise<channels.BrowserNewBrowserCDPSessionResult> {- if (!this._object.options.isChromium)- throw new Error(`CDP session is only available in Chromium`);- const crBrowser = this._object as CRBrowser;- return { session: new CDPSessionDispatcher(this as any as BrowserDispatcher, await crBrowser.newBrowserCDPSession()) };- }-- async startTracing(params: channels.BrowserStartTracingParams): Promise<void> {- if (!this._object.options.isChromium)- throw new Error(`Tracing is only available in Chromium`);- const crBrowser = this._object as CRBrowser;- await crBrowser.startTracing(params.page ? (params.page as PageDispatcher)._object : undefined, params);- }-- async stopTracing(): Promise<channels.BrowserStopTracingResult> {- if (!this._object.options.isChromium)- throw new Error(`Tracing is only available in Chromium`);- const crBrowser = this._object as CRBrowser;- return { artifact: ArtifactDispatcher.from(this, await crBrowser.stopTracing()) };- }async cleanupContexts() {- await Promise.all(Array.from(this._contexts).map(context => context.close({ reason: 'Global context cleanup (connection terminated)' })));- }-}--async function newContextForReuse(browser: Browser, scope: BrowserDispatcher, params: channels.BrowserNewContextForReuseParams, metadata: CallMetadata): Promise<channels.BrowserNewContextForReuseResult> {- const { context, needsReset } = await browser.newContextForReuse(params, metadata);- if (needsReset) {- const oldContextDispatcher = scope.connection.existingDispatcher<BrowserContextDispatcher>(context);- if (oldContextDispatcher)- oldContextDispatcher._dispose();- await context.resetForReuse(metadata, params);+ await Promise.all(Array.from(this._isolatedContexts).map(context => context.close({ reason: 'Global context cleanup (connection terminated)' })));}- const contextDispatcher = BrowserContextDispatcher.from(scope, context);- scope._dispatchEvent('context', { context: contextDispatcher });- return { context: contextDispatcher };}diff --git a/packages/playwright-core/src/server/dispatchers/playwrightDispatcher.ts b/packages/playwright-core/src/server/dispatchers/playwrightDispatcher.tsindex e09ca7ba2c..ec095926d2 100644--- a/packages/playwright-core/src/server/dispatchers/playwrightDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/playwrightDispatcher.ts@@ -18,7 +18,7 @@ import { SocksProxy } from '../utils/socksProxy';import { GlobalAPIRequestContext } from '../fetch';import { AndroidDispatcher } from './androidDispatcher';import { AndroidDeviceDispatcher } from './androidDispatcher';-import { ConnectedBrowserDispatcher } from './browserDispatcher';+import { BrowserDispatcher } from './browserDispatcher';import { BrowserTypeDispatcher } from './browserTypeDispatcher';import { Dispatcher } from './dispatcher';import { ElectronDispatcher } from './electronDispatcher';@@ -35,27 +35,48 @@ import type { Browser } from '../browser';import type { Playwright } from '../playwright';import type * as channels from '@protocol/channels';+type PlaywrightDispatcherOptions = {+ socksProxy?: SocksProxy;+ preLaunchedBrowser?: Browser;+ preLaunchedAndroidDevice?: AndroidDevice;+ sharedBrowser?: boolean;+};+export class PlaywrightDispatcher extends Dispatcher<Playwright, channels.PlaywrightChannel, RootDispatcher> implements channels.PlaywrightChannel {_type_Playwright;- private _browserDispatcher: ConnectedBrowserDispatcher | undefined;+ private _browserDispatcher: BrowserDispatcher | undefined;- constructor(scope: RootDispatcher, playwright: Playwright, socksProxy?: SocksProxy, preLaunchedBrowser?: Browser, prelaunchedAndroidDevice?: AndroidDevice) {- const browserDispatcher = preLaunchedBrowser ? new ConnectedBrowserDispatcher(scope, preLaunchedBrowser) : undefined;+ constructor(scope: RootDispatcher, playwright: Playwright, options: PlaywrightDispatcherOptions = {}) {+ const chromium = new BrowserTypeDispatcher(scope, playwright.chromium);+ const firefox = new BrowserTypeDispatcher(scope, playwright.firefox);+ const webkit = new BrowserTypeDispatcher(scope, playwright.webkit);const android = new AndroidDispatcher(scope, playwright.android);- const prelaunchedAndroidDeviceDispatcher = prelaunchedAndroidDevice ? new AndroidDeviceDispatcher(android, prelaunchedAndroidDevice) : undefined;- super(scope, playwright, 'Playwright', {- chromium: new BrowserTypeDispatcher(scope, playwright.chromium),- firefox: new BrowserTypeDispatcher(scope, playwright.firefox),- webkit: new BrowserTypeDispatcher(scope, playwright.webkit),+ const initializer: channels.PlaywrightInitializer = {+ chromium,+ firefox,+ webkit,bidiChromium: new BrowserTypeDispatcher(scope, playwright.bidiChromium),bidiFirefox: new BrowserTypeDispatcher(scope, playwright.bidiFirefox),android,electron: new ElectronDispatcher(scope, playwright.electron),utils: playwright.options.isServer ? undefined : new LocalUtilsDispatcher(scope, playwright),- preLaunchedBrowser: browserDispatcher,- preConnectedAndroidDevice: prelaunchedAndroidDeviceDispatcher,- socksSupport: socksProxy ? new SocksSupportDispatcher(scope, socksProxy) : undefined,- });+ socksSupport: options.socksProxy ? new SocksSupportDispatcher(scope, options.socksProxy) : undefined,+ };++ let browserDispatcher: BrowserDispatcher | undefined;+ if (options.preLaunchedBrowser) {+ const browserTypeDispatcher = { chromium, firefox, webkit }[options.preLaunchedBrowser.options.name as 'chromium' | 'firefox' | 'webkit'];+ browserDispatcher = new BrowserDispatcher(browserTypeDispatcher, options.preLaunchedBrowser, {+ ignoreStopAndKill: true,+ isolateContexts: !options.sharedBrowser,+ });+ initializer.preLaunchedBrowser = browserDispatcher;+ }++ if (options.preLaunchedAndroidDevice)+ initializer.preConnectedAndroidDevice = new AndroidDeviceDispatcher(android, options.preLaunchedAndroidDevice);++ super(scope, playwright, 'Playwright', initializer);this._type_Playwright = true;this._browserDispatcher = browserDispatcher;}diff --git a/tests/config/remoteServer.ts b/tests/config/remoteServer.tsindex 836e9915f9..94b252a86c 100644--- a/tests/config/remoteServer.ts+++ b/tests/config/remoteServer.ts@@ -68,6 +68,7 @@ export type RemoteServerOptions = {inCluster?: boolean;url?: string;startStopAndRunHttp?: boolean;+ sharedBrowser?: boolean;};export class RemoteServer implements PlaywrightServer {@@ -94,6 +95,8 @@ export class RemoteServer implements PlaywrightServer {handleSIGHUP: true,logger: undefined,};+ if (remoteServerOptions.sharedBrowser)+ (launchOptions as any)._sharedBrowser = true;const options = {browserTypeName: browserType.name(),channel,diff --git a/tests/library/multiclient.spec.ts b/tests/library/multiclient.spec.tsnew file mode 100644index 0000000000..b703735e8f--- /dev/null+++ b/tests/library/multiclient.spec.ts@@ -0,0 +1,68 @@+/**+ * Copyright (c) Microsoft Corporation. All rights reserved.+ *+ * 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 { expect, playwrightTest } from '../config/browserTest';+import type { Browser, BrowserContext, BrowserServer, ConnectOptions, Page } from 'playwright-core';++type ExtraFixtures = {+ remoteServer: BrowserServer;+ connect: (wsEndpoint: string, options?: ConnectOptions) => Promise<Browser>,+};+const test = playwrightTest.extend<ExtraFixtures>({+ remoteServer: async ({ browserType }, use) => {+ const server = await browserType.launchServer({ _sharedBrowser: true } as any);+ await use(server);+ await server.close();+ },+ connect: async ({ browserType }, use) => {+ let browser: Browser | undefined;+ await use(async (wsEndpoint, options = {}) => {+ browser = await browserType.connect(wsEndpoint, options);+ return browser;+ });+ await browser?.close();+ },+});++test.slow(true, 'All connect tests are slow');+test.skip(({ mode }) => mode.startsWith('service'));++test('should connect two clients', async ({ connect, remoteServer, server }) => {+ const browserA = await connect(remoteServer.wsEndpoint());+ expect(browserA.contexts().length).toBe(0);+ const contextA1 = await browserA.newContext();+ const pageA1 = await contextA1.newPage();+ await pageA1.goto(server.EMPTY_PAGE);++ const browserB = await connect(remoteServer.wsEndpoint());+ expect(browserB.contexts().length).toBe(1);+ const contextB1 = browserB.contexts()[0];+ expect(contextB1.pages().length).toBe(1);+ const pageB1 = contextB1.pages()[0];+ await expect(pageB1).toHaveURL(server.EMPTY_PAGE);++ const contextEventPromise = new Promise<BrowserContext>(f => browserA.on('context', f));+ const contextB2 = await browserB.newContext({ baseURL: server.PREFIX });+ expect(browserB.contexts()).toEqual([contextB1, contextB2]);+ const contextA2 = await contextEventPromise;+ expect(browserA.contexts()).toEqual([contextA1, contextA2]);++ const pageEventPromise = new Promise<Page>(f => contextB2.on('page', f));+ const pageA2 = await contextA2.newPage();+ const pageB2 = await pageEventPromise;+ await pageA2.goto('/frames/frame.html');+ await expect(pageB2).toHaveURL('/frames/frame.html');+});