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(webview): generalize dialog bridge into SyncServer (#41878)
Pavel Feldman129717a626d6
diff --git a/packages/playwright-core/src/server/webkit/webview/dialogBridge.ts b/packages/playwright-core/src/server/webkit/webview/syncServer.tssimilarity index 58%rename from packages/playwright-core/src/server/webkit/webview/dialogBridge.tsrename to packages/playwright-core/src/server/webkit/webview/syncServer.tsindex f645a06c1d..71206be999 100644--- a/packages/playwright-core/src/server/webkit/webview/dialogBridge.ts+++ b/packages/playwright-core/src/server/webkit/webview/syncServer.ts@@ -14,30 +14,31 @@* limitations under the License.*/+import { createGuid } from '@utils/crypto';import { debugLogger } from '@utils/debugLogger';import { createHttpServer } from '@utils/network';import type { IncomingMessage, Server, ServerResponse } from 'http';-export type DialogRequest = {- type: 'alert' | 'confirm' | 'prompt';- message: string;- defaultValue: string;-};+// Receives the parsed JSON request body and returns a value that is serialized+// back to the caller as JSON.+type SyncHandler = (body: any) => Promise<any>;-export type DialogResult = {- accept: boolean;- promptText?: string;+export type SyncHandlerRegistration = {+ endpoint: string;+ dispose(): void;};-type DialogHandler = (req: DialogRequest) => Promise<DialogResult>;--export class DialogBridge {+// Small HTTP server that lets page-side scripts perform synchronous XHR calls+// into the server. Each handler is registered under an unguessable guid path so+// the endpoint cannot be discovered by a script running in the page just by+// knowing the (randomly bound) port.+export class SyncServer {private readonly _server: Server;private readonly _baseUrl: string;- private readonly _handlers = new Map<string, DialogHandler>();+ private readonly _handlers = new Map<string, SyncHandler>();- static async start(): Promise<DialogBridge> {+ static async start(): Promise<SyncServer> {const server = createHttpServer();await new Promise<void>((resolve, reject) => {server.once('error', reject);@@ -48,8 +49,8 @@ export class DialogBridge {});const address = server.address();if (!address || typeof address === 'string')- throw new Error('DialogBridge: failed to bind HTTP server');- return new DialogBridge(server, `http://127.0.0.1:${address.port}`);+ throw new Error('SyncServer: failed to bind HTTP server');+ return new SyncServer(server, `http://127.0.0.1:${address.port}`);}private constructor(server: Server, baseUrl: string) {@@ -58,16 +59,13 @@ export class DialogBridge {this._server.on('request', (req, res) => this._handleRequest(req, res));}- endpointFor(pageId: string): string {- return `${this._baseUrl}/dialog?tab=${encodeURIComponent(pageId)}`;- }-- registerTab(pageId: string, handler: DialogHandler): void {- this._handlers.set(pageId, handler);- }-- unregisterTab(pageId: string): void {- this._handlers.delete(pageId);+ addHandler(handler: SyncHandler): SyncHandlerRegistration {+ const guid = createGuid();+ this._handlers.set(guid, handler);+ return {+ endpoint: `${this._baseUrl}/${guid}`,+ dispose: () => this._handlers.delete(guid),+ };}async close(): Promise<void> {@@ -91,16 +89,9 @@ export class DialogBridge {}const url = new URL(req.url || '/', this._baseUrl);- if (!(req.method === 'POST' && url.pathname === '/dialog')) {- res.statusCode = 404;- res.end();- return;- }-- const tab = url.searchParams.get('tab') || '';- const handler = this._handlers.get(tab);- if (!handler) {- // Either the tab is gone or the page raced ahead of registerTab. Reply+ const handler = this._handlers.get(url.pathname.slice(1));+ if (req.method !== 'POST' || !handler) {+ // Either the handler is gone or the page raced ahead of addHandler. Reply// 404 so the page-side override silently falls through.res.statusCode = 404;res.end();@@ -111,18 +102,11 @@ export class DialogBridge {req.setEncoding('utf8');req.on('data', chunk => { body += chunk; });req.on('end', async () => {- let parsed: DialogRequest;+ let parsed: any;try {- const json = JSON.parse(body);- if (json.type !== 'alert' && json.type !== 'confirm' && json.type !== 'prompt')- throw new Error(`Invalid dialog type: ${json.type}`);- parsed = {- type: json.type,- message: typeof json.message === 'string' ? json.message : '',- defaultValue: typeof json.defaultValue === 'string' ? json.defaultValue : '',- };+ parsed = JSON.parse(body);} catch (e) {- debugLogger.log('error', `DialogBridge: bad request body: ${(e as Error).message}`);+ debugLogger.log('error', `SyncServer: bad request body: ${(e as Error).message}`);res.statusCode = 400;res.end();return;@@ -132,12 +116,9 @@ export class DialogBridge {const result = await handler(parsed);res.statusCode = 200;res.setHeader('Content-Type', 'application/json');- res.end(JSON.stringify({- accept: !!result.accept,- promptText: result.promptText,- }));+ res.end(JSON.stringify(result));} catch (e) {- debugLogger.log('error', `DialogBridge: handler error: ${(e as Error).message}`);+ debugLogger.log('error', `SyncServer: handler error: ${(e as Error).message}`);res.statusCode = 500;res.end();}diff --git a/packages/playwright-core/src/server/webkit/webview/wvBrowser.ts b/packages/playwright-core/src/server/webkit/webview/wvBrowser.tsindex bfc8160b2e..77b7f89d98 100644--- a/packages/playwright-core/src/server/webkit/webview/wvBrowser.ts+++ b/packages/playwright-core/src/server/webkit/webview/wvBrowser.ts@@ -29,7 +29,7 @@ import * as network from '../../network';import { perMessageDeflate } from '../../transport';import { getUserAgent } from '../../userAgent';import { BrowserContext } from '../../browserContext';-import { DialogBridge } from './dialogBridge';+import { SyncServer } from './syncServer';import { WVConnection } from './wvConnection';import { WVPage } from './wvPage';@@ -143,8 +143,8 @@ export async function connectOverRDP(progress: Progress, parent: SdkObject, para};const browser = await progress.race((async () => {- const dialogBridge = await DialogBridge.start();- const created = new WVBrowser(parent, proxyBase, headersMap!, dialogBridge, transport, {+ const syncServer = await SyncServer.start();+ const created = new WVBrowser(parent, proxyBase, headersMap!, syncServer, transport, {slowMo: params.slowMo,name: 'webkit',browserType: 'webkit',@@ -158,7 +158,7 @@ export async function connectOverRDP(progress: Progress, parent: SdkObject, para});const shutdown = async () => {await created._closeAllTabs();- await dialogBridge.close().catch(() => {});+ await syncServer.close().catch(() => {});await doCleanup();};created.options.browserProcess = { close: shutdown, kill: shutdown };@@ -183,18 +183,18 @@ export class WVBrowser extends Browser {readonly _context: WVBrowserContext;readonly _proxyBase: string;readonly _headers: { [key: string]: string };- readonly _dialogBridge: DialogBridge;+ readonly _syncServer: SyncServer;readonly _directPageTransport: ConnectOverCDPTransport | undefined;readonly _tabs = new Map<string, TabEntry>();private _didCloseFired = false;// Backwards compat — old code still reads `_page` for the "primary" tab._page!: WVPage;- constructor(parent: SdkObject, proxyBase: string, headers: { [key: string]: string }, dialogBridge: DialogBridge, directPageTransport: ConnectOverCDPTransport | undefined, options: BrowserOptions) {+ constructor(parent: SdkObject, proxyBase: string, headers: { [key: string]: string }, syncServer: SyncServer, directPageTransport: ConnectOverCDPTransport | undefined, options: BrowserOptions) {super(parent, options);this._proxyBase = proxyBase;this._headers = headers;- this._dialogBridge = dialogBridge;+ this._syncServer = syncServer;this._directPageTransport = directPageTransport;this._context = new WVBrowserContext(this);}@@ -238,9 +238,7 @@ export class WVBrowser extends Browser {private async _attachTab(pageId: string, transport: ConnectOverCDPTransport): Promise<void> {const connection = new WVConnection(transport, () => this._detachTab(pageId), this.options.protocolLogger, this.options.browserLogsCollector);- const dialogEndpoint = this._dialogBridge.endpointFor(pageId);- const page = new WVPage(this._context, connection.outerSession, dialogEndpoint);- this._dialogBridge.registerTab(pageId, req => page.onBridgeDialog(req));+ const page = new WVPage(this._context, connection.outerSession, this._syncServer);this._tabs.set(pageId, { pageId, transport, connection, page });transport.open?.();await page.waitForInitialized();@@ -251,7 +249,6 @@ export class WVBrowser extends Browser {if (!entry)return;this._tabs.delete(pageId);- this._dialogBridge.unregisterTab(pageId);entry.connection.close();entry.page.didClose();}diff --git a/packages/playwright-core/src/server/webkit/webview/wvPage.ts b/packages/playwright-core/src/server/webkit/webview/wvPage.tsindex 905c83294a..8147a440e9 100644--- a/packages/playwright-core/src/server/webkit/webview/wvPage.ts+++ b/packages/playwright-core/src/server/webkit/webview/wvPage.ts@@ -40,6 +40,7 @@ import { WVWorkers } from './wvWorkers';import { WVInterceptableRequest, WVRouteImpl } from './wvInterceptableRequest';import { WVProvisionalPage } from './wvProvisionalPage';+import type { SyncHandlerRegistration, SyncServer } from './syncServer';import type { Protocol } from './protocol';import type { WVBrowserContext } from './wvBrowser';import type { RegisteredListener } from '@utils/eventsHelper';@@ -75,11 +76,10 @@ export class WVPage implements PageDelegate {private readonly _requestIdToResponseReceivedPayloadEvent = new Map<string, Protocol.Network.responseReceivedPayload>();private _timestampBaselineForWebSocket = new Map<string, number>();- private readonly _dialogEndpoint: string | undefined;+ private readonly _dialogHandler: SyncHandlerRegistration | undefined;- constructor(browserContext: WVBrowserContext, outerSession: WVSession, dialogEndpoint?: string) {+ constructor(browserContext: WVBrowserContext, outerSession: WVSession, syncServer?: SyncServer) {this._outerSession = outerSession;- this._dialogEndpoint = dialogEndpoint;this.rawKeyboard = new RawKeyboardImpl(this);this.rawMouse = new RawMouseImpl(this);this.rawTouchscreen = new RawTouchscreenImpl(this);@@ -100,6 +100,8 @@ export class WVPage implements PageDelegate {});// Avoid unhandled rejection on disconnect in the middle of initialization.this._firstNonInitialNavigationCommittedPromise.catch(() => {});++ this._dialogHandler = syncServer?.addHandler(body => this._onBridgeDialog(body));}waitForInitialized(): Promise<void> {@@ -244,9 +246,9 @@ export class WVPage implements PageDelegate {// currently-loaded document too — bootstrap only applies to future navigations.await session.sendMayFail('Runtime.evaluate', { expression: webViewInputBootstrapSource, returnByValue: true } as any);await session.sendMayFail('Runtime.evaluate', { expression: sameDocumentNavigationBridgeSource, returnByValue: true } as any);- if (this._dialogEndpoint) {+ if (this._dialogHandler) {await session.sendMayFail('Runtime.evaluate', {- expression: dialogBridgeSource(this._dialogEndpoint),+ expression: dialogBridgeSource(this._dialogHandler.endpoint),returnByValue: true,} as any);}@@ -339,19 +341,25 @@ export class WVPage implements PageDelegate {}}- async onBridgeDialog(req: { type: 'alert' | 'confirm' | 'prompt'; message: string; defaultValue: string }): Promise<{ accept: boolean; promptText?: string }> {+ private async _onBridgeDialog(body: any): Promise<{ accept: boolean; promptText?: string }> {+ const type = body?.type;+ if (type !== 'alert' && type !== 'confirm' && type !== 'prompt')+ throw new Error(`Invalid dialog type: ${type}`);+ const message = typeof body?.message === 'string' ? body.message : '';+ const defaultValue = typeof body?.defaultValue === 'string' ? body.defaultValue : '';return await new Promise<{ accept: boolean; promptText?: string }>(resolve => {this._page.browserContext.dialogManager.dialogDidOpen(new dialog.Dialog(this._page,- req.type,- req.message,+ type,+ message,async (accept: boolean, promptText?: string) => resolve({ accept, promptText }),- req.defaultValue,+ defaultValue,));});}didClose() {+ this._dialogHandler?.dispose();eventsHelper.removeEventListeners(this._sessionListeners);eventsHelper.removeEventListeners(this._eventListeners);if (this._session)@@ -704,8 +712,8 @@ export class WVPage implements PageDelegate {scripts.push(bindingBridgeSource);scripts.push(sameDocumentNavigationBridgeSource);scripts.push(webViewInputBootstrapSource);- if (this._dialogEndpoint)- scripts.push(dialogBridgeSource(this._dialogEndpoint));+ if (this._dialogHandler)+ scripts.push(dialogBridgeSource(this._dialogHandler.endpoint));scripts.push(...this._page.allInitScripts().map(script => script.source));return scripts.join(';\n');}