Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions packages/extension/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,6 @@ If the extension is installed in several Chrome profiles, the connection is made

The `PLAYWRIGHT_MCP_PROFILE_DIR_NAME` environment variable can be used instead of the option. The authentication token is specific to the profile, so use the one displayed in that profile.

## Troubleshooting

Chrome does not allow extensions to debug a page that contains a frame with a restricted URL, for example a page of another extension (`chrome-extension://`), a `chrome://` page, or a URL with a custom scheme. When such a frame loads, Chrome detaches the Playwright debugger. If the frame stays in the page, the tab is no longer available to the client. This often happens when another extension adds its own frame to every page. Disable that extension on the sites you automate, set its **Site access** to **On click**, or use a profile without it. Then navigate again.
1 change: 1 addition & 0 deletions packages/playwright-core/src/tools/backend/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export type ContextConfig = {
capabilities?: ToolCapability[];
codegen?: 'typescript' | 'python' | 'java' | 'csharp' | 'none';
console?: { level?: 'error' | 'warning' | 'info' | 'debug' };
extension?: boolean;
imageResponses?: 'allow' | 'omit' | 'only';
filePaths?: 'relative' | 'absolute';
network?: {
Expand Down
10 changes: 9 additions & 1 deletion packages/playwright-core/src/tools/backend/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,15 @@ export class Response {
if (this._includeSnapshot !== 'none' || tabHeaders.some(header => header.changed)) {
if (tabHeaders.length !== 1)
addSection('Open tabs', renderTabsMarkdown(tabHeaders));
addSection('Page', renderTabMarkdown(tabHeaders.find(h => h.current) ?? tabHeaders[0]));
const currentTab = tabHeaders.find(h => h.current) ?? tabHeaders[0];
if (currentTab) {
addSection('Page', renderTabMarkdown(currentTab));
} else if (this._includeSnapshot !== 'none' && !this._errors.length) {
const error = ['No open tabs. The page was closed before a snapshot could be captured.'];
if (this._context.config.extension)
error.push(`Chrome may have detached the debugger because the page contains a frame that extensions are not allowed to debug, for example a frame added by another extension. If so, set that extension's site access to "On click" and navigate again.`);
addSection('Error', error);
}
}

// Handle modal states.
Expand Down
9 changes: 5 additions & 4 deletions tests/extension/extension-fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import type { StartClient } from '../mcp/fixtures';

export type BrowserWithExtension = {
userDataDir: string;
launch: (mode?: 'disable-extension') => Promise<BrowserContext>;
launch: (mode?: 'disable-extension', additionalExtensions?: string[]) => Promise<BrowserContext>;
};

export type CliResult = {
Expand Down Expand Up @@ -65,16 +65,17 @@ export const test = base.extend<TestFixtures>({
await fs.mkdir(path.join(userDataDir, 'Default', 'Extensions', extensionId), { recursive: true });
await use({
userDataDir,
launch: async (mode?: 'disable-extension') => {
launch: async (mode?: 'disable-extension', additionalExtensions: string[] = []) => {
const extensions = [pathToExtension, ...additionalExtensions].join(',');
browserContext = await chromium.launchPersistentContext(userDataDir, {
channel: mcpBrowser,
// Opening the browser singleton only works in headed.
headless: false,
// Automation disables singleton browser process behavior, which is necessary for the extension.
ignoreDefaultArgs: ['--enable-automation'],
args: mode === 'disable-extension' ? [] : [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`,
`--disable-extensions-except=${extensions}`,
`--load-extension=${extensions}`,
],
});

Expand Down
43 changes: 43 additions & 0 deletions tests/extension/scheme-detach.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
* limitations under the License.
*/

import fs from 'fs/promises';
import path from 'path';
import { test, expect, extensionId, connectWithToken } from './extension-fixtures';

import type { BrowserContext } from 'playwright';
Expand Down Expand Up @@ -98,3 +100,44 @@ test('recovers and can screenshot after the debugger is detached', {
code: expect.stringContaining('page.screenshot'),
});
});

test('reports an error instead of crashing when another extension frame detaches the debugger', {
annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43230' },
}, async ({ browserWithExtension, startClient, server }, testInfo) => {
const injector = testInfo.outputPath('frame-injector');
await fs.mkdir(injector);
await fs.writeFile(path.join(injector, 'manifest.json'), JSON.stringify({
manifest_version: 3,
name: 'Frame injector',
version: '1.0',
content_scripts: [{ matches: ['http://*/*'], js: ['content.js'], run_at: 'document_idle' }],
web_accessible_resources: [{ resources: ['frame.html'], matches: ['<all_urls>'] }],
}));
await fs.writeFile(path.join(injector, 'content.js'), `
if (location.pathname === '/hello-world') {
const frame = document.createElement('iframe');
frame.src = chrome.runtime.getURL('frame.html');
document.documentElement.appendChild(frame);
}
`);
await fs.writeFile(path.join(injector, 'frame.html'), '<!DOCTYPE html><title>Foreign frame</title>');

const browserContext = await browserWithExtension.launch(undefined, [injector]);
const { client } = await connectWithToken(browserContext, startClient, browserWithExtension.userDataDir);
const getDetach = await watchDetach(browserContext);

const response = await client.callTool({ name: 'browser_navigate', arguments: { url: server.HELLO_WORLD } });
expect(response).toHaveResponse({
isError: true,
error: expect.stringContaining('frame that extensions are not allowed to debug'),
});
expect(JSON.stringify(response)).not.toContain('TypeError');
await expect.poll(getDetach).toEqual(expect.arrayContaining([
expect.objectContaining({ reason: 'target_closed' }),
]));

server.setContent('/recovered', '<body>Recovered</body>', 'text/html');
expect(await client.callTool({ name: 'browser_navigate', arguments: { url: server.PREFIX + '/recovered' } })).toHaveResponse({
snapshot: expect.stringContaining('Recovered'),
});
});
Loading