Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(extension): recover the debugger after an involuntary detach (#42221)

Yury Semikhatskyffbfb2746e30
diff --git a/packages/extension/src/relayConnection.ts b/packages/extension/src/relayConnection.ts
index 7ef2646d3f..928820ef97 100644
--- a/packages/extension/src/relayConnection.ts
+++ b/packages/extension/src/relayConnection.ts
@@ -54,6 +54,10 @@ const CHROME_EVENT_METHODS = [
'chrome.tabs.onRemoved',
];
+const REATTACH_DELAY_MS = 150;
+const REATTACH_VERIFY_MS = 2500;
+const REATTACH_COOLDOWN_MS = 3000;
+
export class RelayConnection {
private _ws: WebSocket;
// Tabs whose debugger we have explicitly attached for this connection.
@@ -62,6 +66,8 @@ export class RelayConnection {
private _hasEverAttached = false;
private _eventListeners: Array<{ remove: () => void }> = [];
private _closed = false;
+ private _pendingReattach = new Set<number>();
+ private _recentReattach = new Set<number>();
onclose?: () => void;
ontabattached?: (tabId: number) => void;
@@ -125,6 +131,7 @@ export class RelayConnection {
private _notifyTabAttached(tabId: number): void {
this._attachedTabs.add(tabId);
this._hasEverAttached = true;
+ this._pendingReattach.delete(tabId);
this.ontabattached?.(tabId);
}
@@ -148,6 +155,8 @@ export class RelayConnection {
if (this._closed)
return;
this._closed = true;
+ this._pendingReattach.clear();
+ this._recentReattach.clear();
for (const l of this._eventListeners)
l.remove();
this._eventListeners = [];
@@ -159,7 +168,7 @@ export class RelayConnection {
}
private _checkLastTabDetached(): void {
- if (this._hasEverAttached && this._attachedTabs.size === 0)
+ if (this._hasEverAttached && this._attachedTabs.size === 0 && this._pendingReattach.size === 0)
this.close('All controlled tabs detached');
}
@@ -172,11 +181,59 @@ export class RelayConnection {
this._sendMessage({ method: fullMethod, params: args });
// chrome.debugger.onDetach is the single source of truth for detach bookkeeping.
if (fullMethod === 'chrome.debugger.onDetach') {
+ const reason = args[1] as string | undefined;
this._notifyTabDetached(tabId);
+ if (reason === 'target_closed' && this._maybeScheduleReattach(tabId))
+ return;
this._checkLastTabDetached();
}
}
+ private _maybeScheduleReattach(tabId: number): boolean {
+ if (this._closed)
+ return false;
+ if (this._recentReattach.has(tabId)) {
+ debugLog(`Not re-attaching tab ${tabId}: re-detached within ${REATTACH_COOLDOWN_MS}ms`);
+ return false;
+ }
+ this._recentReattach.add(tabId);
+ setTimeout(() => this._recentReattach.delete(tabId), REATTACH_COOLDOWN_MS);
+ this._pendingReattach.add(tabId);
+ setTimeout(() => void this._tryReattach(tabId), REATTACH_DELAY_MS);
+ return true;
+ }
+
+ private _reattachAborted(tabId: number): boolean {
+ return this._closed || !this._pendingReattach.has(tabId);
+ }
+
+ private async _tryReattach(tabId: number): Promise<void> {
+ if (this._reattachAborted(tabId))
+ return;
+ let tab: chrome.tabs.Tab | undefined;
+ try {
+ tab = await chrome.tabs.get(tabId);
+ } catch {
+ this._pendingReattach.delete(tabId);
+ this._checkLastTabDetached();
+ return;
+ }
+ if (this._reattachAborted(tabId))
+ return;
+ if (this._attachedTabs.has(tabId)) {
+ this._pendingReattach.delete(tabId);
+ return;
+ }
+ this.attachTab(tab);
+ setTimeout(() => {
+ if (this._reattachAborted(tabId))
+ return;
+ this._pendingReattach.delete(tabId);
+ if (!this._attachedTabs.has(tabId))
+ this._checkLastTabDetached();
+ }, REATTACH_VERIFY_MS);
+ }
+
// Returns the tabId an event refers to, for filtering by _attachedTabs.
private _tabIdForEventArgs(fullMethod: string, args: any[]): number | undefined {
switch (fullMethod) {
diff --git a/tests/extension/extension-fixtures.ts b/tests/extension/extension-fixtures.ts
index 8594364908..760c78fdaf 100644
--- a/tests/extension/extension-fixtures.ts
+++ b/tests/extension/extension-fixtures.ts
@@ -206,6 +206,19 @@ export async function readExtensionToken(browserContext: BrowserContext): Promis
return value;
}
+export async function connectWithToken(browserContext: BrowserContext, startClient: StartClient, userDataDir: string): Promise<{ client: Client, stderr: () => string }> {
+ const token = await readExtensionToken(browserContext);
+ const { client, stderr } = await startClient({
+ args: ['--extension'],
+ env: {
+ DEBUG: 'pw:mcp:backend',
+ PLAYWRIGHT_MCP_EXTENSION_TOKEN: token,
+ PWTEST_EXTENSION_USER_DATA_DIR: userDataDir,
+ },
+ });
+ return { client, stderr };
+}
+
// The connect page closes itself once a different tab is selected, which races
// with the click — the request reaches the background while the page is being
// torn down. Swallow the resulting "Target closed" error.
diff --git a/tests/extension/scheme-detach.spec.ts b/tests/extension/scheme-detach.spec.ts
new file mode 100644
index 0000000000..f541afad84
--- /dev/null
+++ b/tests/extension/scheme-detach.spec.ts
@@ -0,0 +1,106 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * 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 { test, expect, extensionId, connectWithToken } from './extension-fixtures';
+
+import type { BrowserContext } from 'playwright';
+
+async function watchDetach(browserContext: BrowserContext) {
+ const serviceWorker = browserContext.serviceWorkers().find(w => w.url().includes(extensionId))!;
+ await serviceWorker.evaluate(() => {
+ (globalThis as any).__detach = [];
+ (globalThis as any).chrome.debugger.onDetach.addListener((source: any, reason: string) => {
+ (globalThis as any).__detach.push({ source, reason });
+ });
+ });
+ return () => serviceWorker.evaluate(() => (globalThis as any).__detach);
+}
+
+test('debugger detaches from the whole tab when a subframe navigates to an unknown scheme', {
+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42089' },
+}, async ({ browserWithExtension, startClient, server }) => {
+ const browserContext = await browserWithExtension.launch();
+ const { client } = await connectWithToken(browserContext, startClient, browserWithExtension.userDataDir);
+
+ server.setContent('/signin', `<title>SignIn</title><div>QR CODE HERE</div>`, 'text/html');
+ await client.callTool({ name: 'browser_navigate', arguments: { url: server.PREFIX + '/signin' } });
+
+ const getDetach = await watchDetach(browserContext);
+ const page = browserContext.pages().find(p => p.url().endsWith('/signin'))!;
+ await page.evaluate(() => {
+ const iframe = document.createElement('iframe');
+ iframe.src = 'customscheme://cc/';
+ document.body.appendChild(iframe);
+ }).catch(() => {});
+
+ await expect.poll(async () => (await getDetach()).length, { timeout: 5000 }).toBeGreaterThan(0);
+ const detach = await getDetach();
+ expect(detach[0].reason).toBe('target_closed');
+ expect(detach[0].source.frameId).toBeUndefined();
+
+ expect(page.url()).toContain('/signin');
+ expect(await page.title()).toBe('SignIn');
+});
+
+test('recovers and can screenshot after the debugger is detached', {
+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42089' },
+}, async ({ browserWithExtension, startClient, server }) => {
+ const browserContext = await browserWithExtension.launch();
+ const { client } = await connectWithToken(browserContext, startClient, browserWithExtension.userDataDir);
+
+ server.setContent('/signin', `
+ <title>SignIn</title>
+ <div>QR CODE HERE</div>
+ <script>
+ if (!window.__probed) {
+ window.__probed = true;
+ setTimeout(() => {
+ const iframe = document.createElement('iframe');
+ iframe.src = 'customscheme://cc/';
+ document.body.appendChild(iframe);
+ }, 300);
+ }
+ </script>
+ `, 'text/html');
+
+ const getDetach = await watchDetach(browserContext);
+ expect(await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.PREFIX + '/signin' },
+ })).toHaveResponse({ snapshot: expect.stringContaining('QR CODE HERE') });
+
+ await expect.poll(async () => (await getDetach()).length, { timeout: 5000 }).toBeGreaterThan(0);
+ expect((await getDetach())[0].reason).toBe('target_closed');
+
+ expect(browserContext.pages().find(p => p.url().endsWith('/signin'))).toBeTruthy();
+
+ await expect.poll(async () => {
+ const list = await client.callTool({ name: 'browser_tabs', arguments: { action: 'list' } });
+ return (list as any).content?.[0]?.text ?? '';
+ }, { timeout: 15000 }).toContain('/signin');
+
+ const list = await client.callTool({ name: 'browser_tabs', arguments: { action: 'list' } });
+ const index = /- (\d+):[^\n]*\/signin/.exec((list as any).content[0].text)?.[1];
+ expect(index).toBeTruthy();
+ await client.callTool({ name: 'browser_tabs', arguments: { action: 'select', index: Number(index) } });
+
+ expect(await client.callTool({ name: 'browser_snapshot', arguments: {} })).toHaveResponse({
+ inlineSnapshot: expect.stringContaining('QR CODE HERE'),
+ });
+ expect(await client.callTool({ name: 'browser_take_screenshot', arguments: {} })).toHaveResponse({
+ code: expect.stringContaining('page.screenshot'),
+ });
+});