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
feat(cli): list system Chrome/Edge browsers available for CDP attach (#40253)
Pavel Feldmande0e0d22a248
diff --git a/packages/playwright-core/src/tools/cli-client/DEPS.list b/packages/playwright-core/src/tools/cli-client/DEPS.listindex c36e724141..6d5be4ad81 100644--- a/packages/playwright-core/src/tools/cli-client/DEPS.list+++ b/packages/playwright-core/src/tools/cli-client/DEPS.list@@ -2,10 +2,14 @@"strict"../../package.ts../../serverRegistry.ts+./channelSessions.ts./minimist.ts./session.ts./registry.ts+[channelSessions.ts]+"strict"+[session.ts]"strict"../../package.tsdiff --git a/packages/playwright-core/src/tools/cli-client/channelSessions.ts b/packages/playwright-core/src/tools/cli-client/channelSessions.tsnew file mode 100644index 0000000000..d6ae31de5e--- /dev/null+++ b/packages/playwright-core/src/tools/cli-client/channelSessions.ts@@ -0,0 +1,128 @@+/**+ * 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 fs from 'fs';+import net from 'net';+import os from 'os';+import path from 'path';++export type ChannelSession = {+ channel: string;+ userDataDir: string;+ endpoint?: string;+};++export async function listChannelSessions(): Promise<ChannelSession[]> {+ if (process.env.PLAYWRIGHT_CLI_CHANNEL_SCAN_DISABLED_FOR_TEST)+ return [];+ const result: ChannelSession[] = [];+ for (const [channel, dirs] of channelToUserDataDir) {+ const userDataDir = dirs[process.platform];+ if (!userDataDir)+ continue;+ if (!await pathExists(userDataDir))+ continue;+ const endpoint = await readEndpoint(userDataDir);+ result.push({ channel, userDataDir, endpoint });+ }+ return result;+}++export function remoteDebuggingHint(channel: string): string {+ return `to enable, launch ${channel}, navigate to chrome://inspect/#remote-debugging and check "Allow remote debugging for this browser instance"`;+}++async function pathExists(p: string): Promise<boolean> {+ try {+ await fs.promises.access(p);+ return true;+ } catch {+ return false;+ }+}++async function readEndpoint(userDataDir: string): Promise<string | undefined> {+ let contents: string;+ try {+ contents = await fs.promises.readFile(path.join(userDataDir, 'DevToolsActivePort'), 'utf-8');+ } catch {+ return undefined;+ }+ const port = parseInt(contents.trim().split('\n')[0], 10);+ if (!Number.isFinite(port))+ return undefined;+ if (!await isPortOpen(port))+ return undefined;+ return `http://localhost:${port}`;+}++async function isPortOpen(port: number): Promise<boolean> {+ return new Promise(resolve => {+ const socket = net.createConnection(port, '127.0.0.1');+ const done = (value: boolean) => {+ socket.destroy();+ resolve(value);+ };+ socket.once('connect', () => done(true));+ socket.once('error', () => done(false));+ socket.setTimeout(250, () => done(false));+ });+}++// Keep in sync with channelToUserDataDir in+// packages/playwright-core/src/server/chromium/chromium.ts.+const channelToUserDataDir = new Map<string, Record<string, string>>([+ ['chrome', {+ 'linux': path.join(os.homedir(), '.config', 'google-chrome'),+ 'darwin': path.join(os.homedir(), 'Library', 'Application Support', 'Google', 'Chrome'),+ 'win32': path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Google', 'Chrome', 'User Data'),+ }],+ ['chrome-beta', {+ 'linux': path.join(os.homedir(), '.config', 'google-chrome-beta'),+ 'darwin': path.join(os.homedir(), 'Library', 'Application Support', 'Google', 'Chrome Beta'),+ 'win32': path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Google', 'Chrome Beta', 'User Data'),+ }],+ ['chrome-dev', {+ 'linux': path.join(os.homedir(), '.config', 'google-chrome-unstable'),+ 'darwin': path.join(os.homedir(), 'Library', 'Application Support', 'Google', 'Chrome Dev'),+ 'win32': path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Google', 'Chrome Dev', 'User Data'),+ }],+ ['chrome-canary', {+ 'linux': path.join(os.homedir(), '.config', 'google-chrome-canary'),+ 'darwin': path.join(os.homedir(), 'Library', 'Application Support', 'Google', 'Chrome Canary'),+ 'win32': path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Google', 'Chrome SxS', 'User Data'),+ }],+ ['msedge', {+ 'linux': path.join(os.homedir(), '.config', 'microsoft-edge'),+ 'darwin': path.join(os.homedir(), 'Library', 'Application Support', 'Microsoft Edge'),+ 'win32': path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Microsoft', 'Edge', 'User Data'),+ }],+ ['msedge-beta', {+ 'linux': path.join(os.homedir(), '.config', 'microsoft-edge-beta'),+ 'darwin': path.join(os.homedir(), 'Library', 'Application Support', 'Microsoft Edge Beta'),+ 'win32': path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Microsoft', 'Edge Beta', 'User Data'),+ }],+ ['msedge-dev', {+ 'linux': path.join(os.homedir(), '.config', 'microsoft-edge-dev'),+ 'darwin': path.join(os.homedir(), 'Library', 'Application Support', 'Microsoft Edge Dev'),+ 'win32': path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Microsoft', 'Edge Dev', 'User Data'),+ }],+ ['msedge-canary', {+ 'linux': path.join(os.homedir(), '.config', 'microsoft-edge-canary'),+ 'darwin': path.join(os.homedir(), 'Library', 'Application Support', 'Microsoft Edge Canary'),+ 'win32': path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Microsoft', 'Edge SxS', 'User Data'),+ }],+]);diff --git a/packages/playwright-core/src/tools/cli-client/program.ts b/packages/playwright-core/src/tools/cli-client/program.tsindex 592fa05a31..9b297185db 100644--- a/packages/playwright-core/src/tools/cli-client/program.ts+++ b/packages/playwright-core/src/tools/cli-client/program.ts@@ -22,6 +22,7 @@ import { execSync, spawn } from 'child_process';import crypto from 'crypto';import os from 'os';import path from 'path';+import { listChannelSessions, remoteDebuggingHint } from './channelSessions';import { clientKey, createClientInfo, explicitSessionName, Registry, resolveSessionName } from './registry';import { Session, renderResolvedConfig } from './session';import { libPath } from '../../package';@@ -323,6 +324,25 @@ async function listSessions(registry: Registry, clientInfo: ClientInfo, all: booif (!count)console.log(' (no browsers)');++ const channelSessions = await listChannelSessions();+ if (channelSessions.length) {+ console.log('');+ console.log('### Browsers available to attach via CDP');+ for (const session of channelSessions) {+ const text: string[] = [];+ text.push(`- ${session.channel}:`);+ text.push(` - data-dir: ${session.userDataDir}`);+ if (session.endpoint) {+ text.push(` - endpoint: ${session.endpoint}`);+ text.push(` - run \`playwright-cli attach --cdp=${session.channel}\` to attach`);+ } else {+ text.push(` - status: remote debugging not enabled`);+ text.push(` - ${remoteDebuggingHint(session.channel)}`);+ }+ console.log(text.join('\n'));+ }+ }}async function gcAndPrintSessions(clientInfo: ClientInfo, sessions: Session[], header?: string, runningSessions?: Set<string>) {diff --git a/tests/mcp/cli-fixtures.ts b/tests/mcp/cli-fixtures.tsindex c44eb2554f..e31a3f5919 100644--- a/tests/mcp/cli-fixtures.ts+++ b/tests/mcp/cli-fixtures.ts@@ -97,6 +97,7 @@ function cliEnv() {PLAYWRIGHT_DASHBOARD_SETTINGS_FILE_FOR_TEST: test.info().outputPath('dashboard.settings.json'),PLAYWRIGHT_DAEMON_SESSION_DIR: test.info().outputPath('daemon'),PLAYWRIGHT_SOCKETS_DIR: path.join(test.info().project.outputDir, 'ds', String(test.info().parallelIndex)),+ PLAYWRIGHT_CLI_CHANNEL_SCAN_DISABLED_FOR_TEST: '1',};}