Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/playwright-core/src/client/browserType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
isLocal: params.isLocal,
noDefaults: params.noDefaults,
isWebView: (params as any).isWebView,
pageInitTimeout: (params as any).pageInitTimeout,
artifactsDir: params.artifactsDir,
}, new TimeoutSettings().timeout(params));
return await this._browserFromConnectResult(result);
Expand Down
2 changes: 2 additions & 0 deletions packages/playwright-core/src/client/channels.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2058,6 +2058,7 @@ export type BrowserTypeConnectOverCDPParams = {
isLocal?: boolean,
noDefaults?: boolean,
isWebView?: boolean,
pageInitTimeout?: number,
artifactsDir?: string,
transport?: Binary,
};
Expand All @@ -2068,6 +2069,7 @@ export type BrowserTypeConnectOverCDPOptions = {
isLocal?: boolean,
noDefaults?: boolean,
isWebView?: boolean,
pageInitTimeout?: number,
artifactsDir?: string,
transport?: Binary,
};
Expand Down
2 changes: 2 additions & 0 deletions packages/playwright-core/src/server/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ export type BrowserOptions = {
userDataDir?: string;
noDefaults?: boolean;
isWebView?: boolean;
// Maximum time to wait for the existing pages while connecting. Slower pages are reported later.
pageInitTimeout?: number;
// Do not send Inspector.enable to detect pages without a renderer while connecting.
noInspectorEnableOnConnect?: boolean;
};
Expand Down
2 changes: 2 additions & 0 deletions packages/playwright-core/src/server/channels.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2059,6 +2059,7 @@ export type BrowserTypeConnectOverCDPParams = {
isLocal?: boolean,
noDefaults?: boolean,
isWebView?: boolean,
pageInitTimeout?: number,
artifactsDir?: string,
transport?: Binary,
};
Expand All @@ -2069,6 +2070,7 @@ export type BrowserTypeConnectOverCDPOptions = {
isLocal?: boolean,
noDefaults?: boolean,
isWebView?: boolean,
pageInitTimeout?: number,
artifactsDir?: string,
transport?: Binary,
};
Expand Down
5 changes: 3 additions & 2 deletions packages/playwright-core/src/server/chromium/chromium.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class Chromium extends BrowserType {
return await this._connectOverCDPInternal(progress, params.endpointURL!, params);
}

async _connectOverCDPInternal(progress: Progress, endpointURL: string, options: types.LaunchOptions & { headers?: types.HeadersArray, isLocal?: boolean, noDefaults?: boolean, isWebView?: boolean, artifactsDir?: string }, onClose?: () => Promise<void>) {
async _connectOverCDPInternal(progress: Progress, endpointURL: string, options: types.LaunchOptions & { headers?: types.HeadersArray, isLocal?: boolean, noDefaults?: boolean, isWebView?: boolean, pageInitTimeout?: number, artifactsDir?: string }, onClose?: () => Promise<void>) {
let headersMap: { [key: string]: string; } | undefined;
if (options.headers)
headersMap = headersArrayToObject(options.headers, false);
Expand Down Expand Up @@ -111,7 +111,7 @@ export class Chromium extends BrowserType {
return this._connectOverCDPImpl(progress, chromeTransport, closeAndWait, options, onClose);
}

private async _connectOverCDPImpl(progress: Progress, transport: ConnectionTransport, closeAndWait: () => Promise<void>, options: types.LaunchOptions & { isLocal?: boolean, noDefaults?: boolean, isWebView?: boolean, artifactsDir?: string }, onClose?: () => Promise<void>) {
private async _connectOverCDPImpl(progress: Progress, transport: ConnectionTransport, closeAndWait: () => Promise<void>, options: types.LaunchOptions & { isLocal?: boolean, noDefaults?: boolean, isWebView?: boolean, pageInitTimeout?: number, artifactsDir?: string }, onClose?: () => Promise<void>) {
let artifactsDir: string;
const tempDirectories: string[] = [];
if (options.artifactsDir) {
Expand Down Expand Up @@ -152,6 +152,7 @@ export class Chromium extends BrowserType {
originalLaunchOptions: {},
noDefaults: options.noDefaults,
isWebView: options.isWebView,
pageInitTimeout: options.pageInitTimeout,
};
validateBrowserContextOptions(persistent, browserOptions);
const browser = await progress.race(CRBrowser.connect(this.attribution.playwright, transport, browserOptions));
Expand Down
14 changes: 11 additions & 3 deletions packages/playwright-core/src/server/chromium/crBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export class CRBrowser extends Browser {
}),
browser._defaultContext.initialize(),
]);
await browser._waitForAllPagesToBeInitialized();
await browser._waitForAllPagesToBeInitialized(options.pageInitTimeout);
} finally {
browser._isConnecting = false;
}
Expand Down Expand Up @@ -178,8 +178,16 @@ export class CRBrowser extends Browser {
return this.options.name === 'clank';
}

async _waitForAllPagesToBeInitialized() {
await Promise.all([...this._crPages.values()].map(crPage => crPage._page.waitForInitializedOrError()));
async _waitForAllPagesToBeInitialized(timeout?: number) {
const allPages = Promise.all([...this._crPages.values()].map(crPage => crPage._page.waitForInitializedOrError()));
if (!timeout) {
await allPages;
return;
}
// Pages that are not ready in time, e.g. with a busy renderer, are reported later.
let timer: NodeJS.Timeout | undefined;
await Promise.race([allPages, new Promise(f => timer = setTimeout(f, timeout))]);
clearTimeout(timer);
}

_onAttachedToTarget({ targetInfo, sessionId, waitingForDebugger }: Protocol.Target.attachedToTargetPayload) {
Expand Down
4 changes: 3 additions & 1 deletion packages/playwright-core/src/tools/mcp/browserFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,9 @@ async function createCDPBrowser(config: FullConfig, clientInfo: ClientInfo): Pro
timeout: config.browser.cdpTimeout,
noDefaults: true,
artifactsDir,
});
// Do not let a page with a busy renderer block the connection.
pageInitTimeout: 10000,
} as playwrightTypes.ConnectOverCDPOptions);
return browser;
}

Expand Down
1 change: 1 addition & 0 deletions packages/protocol/spec/browserType.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ BrowserType:
isLocal: boolean?
noDefaults: boolean?
isWebView: boolean?
pageInitTimeout: float?
artifactsDir: string?
transport: binary?
returns:
Expand Down
1 change: 1 addition & 0 deletions packages/protocol/src/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1121,6 +1121,7 @@ scheme.BrowserTypeConnectOverCDPParams = tObject({
isLocal: tOptional(tBoolean),
noDefaults: tOptional(tBoolean),
isWebView: tOptional(tBoolean),
pageInitTimeout: tOptional(tFloat),
artifactsDir: tOptional(tString),
transport: tOptional(tBinary),
});
Expand Down
44 changes: 44 additions & 0 deletions tests/library/chromium/connect-over-cdp.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -952,6 +952,50 @@ test('CD-036 should connect over CDP using a ConnectionTransport', async ({ brow
}
});

test('CD-054 should not wait for a busy page longer than pageInitTimeout', {
annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/44052' },
}, async ({ browserType, server }, testInfo) => {
const port = 9339 + testInfo.workerIndex;
const browserServer = await browserType.launch({
// The busy page should not share a renderer with the other page.
args: ['--remote-debugging-port=' + port, '--site-per-process']
});
try {
const cdpBrowser1 = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
});
const context1 = cdpBrowser1.contexts()[0];
const page1 = await context1.newPage();
await page1.goto(server.CROSS_PROCESS_PREFIX + '/title.html');
const busyPage1 = await context1.newPage();
await busyPage1.goto(server.EMPTY_PAGE);
const busyStarted = busyPage1.waitForEvent('console', message => message.text() === 'busy');
busyPage1.evaluate(() => {
console.log('busy');
const start = Date.now();
while (Date.now() - start < 5000) {}
}).catch(() => {});
await busyStarted;

const cdpBrowser2 = await browserType.connectOverCDP({
endpointURL: `http://127.0.0.1:${port}/`,
pageInitTimeout: 500,
} as any);
const context2 = cdpBrowser2.contexts()[0];
const pages = context2.pages();
expect(pages.map(page => page.url())).toEqual([server.CROSS_PROCESS_PREFIX + '/title.html']);
expect(await pages[0].title()).toBe('Woof-Woof');
// The busy page is reported when its renderer responds again.
const busyPage2 = await context2.waitForEvent('page');
expect(busyPage2.url()).toBe(server.EMPTY_PAGE);
expect(await busyPage2.evaluate(() => 1 + 1)).toBe(2);
await cdpBrowser2.close();
await cdpBrowser1.close();
} finally {
await browserServer.close();
}
});

test.fixme('CD-053 should connect when another client inspects a terminated shared worker', {
annotation: [
{ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43638' },
Expand Down
25 changes: 25 additions & 0 deletions tests/mcp/cdp.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,31 @@ test('cdp connection uses noDefaults', async ({ cdpServer, startClient }) => {
expect(await page.evaluate(() => matchMedia('print').matches)).toBe(true);
});

test('cdp connection does not wait for a busy page', {
annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/44052' },
}, async ({ cdpServer, startClient, server }) => {
const browserContext = await cdpServer.start();
const [busyPage] = browserContext.pages();
await busyPage.goto(server.CROSS_PROCESS_PREFIX + '/empty.html');
const page = await browserContext.newPage();
await page.goto(server.HELLO_WORLD);
const busyStarted = busyPage.waitForEvent('console', message => message.text() === 'busy');
busyPage.evaluate(() => {
console.log('busy');
for (;;) {}
}).catch(() => {});
await busyStarted;

const { client } = await startClient({ args: [`--cdp-endpoint=${cdpServer.endpoint}`] });
expect(await client.callTool({
name: 'browser_snapshot',
})).toHaveResponse({
page: `- Page URL: ${server.HELLO_WORLD}
- Page Title: Title`,
inlineSnapshot: `- generic [active] [ref=e1]: Hello, world!`,
});
});

test('should throw connection error and allow re-connecting', async ({ cdpServer, startClient, server }) => {
const { client } = await startClient({ args: [`--cdp-endpoint=${cdpServer.endpoint}`] });

Expand Down
1 change: 1 addition & 0 deletions tests/registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -766,6 +766,7 @@ subsystem, add a row to the Subsystems table. Then update this file:
| `CD-051` | `library/chromium/session.spec.ts` | should emit close event when page closes |
| `CD-052` | `library/chromium/session.spec.ts` | should work with newBrowserCDPSession |
| `CD-053` | `library/chromium/connect-over-cdp.spec.ts` | should connect when another client inspects a terminated shared worker |
| `CD-054` | `library/chromium/connect-over-cdp.spec.ts` | should not wait for a busy page longer than pageInitTimeout |

### CF — Code frame

Expand Down
Loading