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(extension): warn when Playwright Extension is missing from profile (#40406)
Yury Semikhatsky780644ff4d3c
diff --git a/packages/playwright-core/src/server/chromium/chromium.ts b/packages/playwright-core/src/server/chromium/chromium.tsindex 7e3a609fe4..a64d074a26 100644--- a/packages/playwright-core/src/server/chromium/chromium.ts+++ b/packages/playwright-core/src/server/chromium/chromium.ts@@ -21,6 +21,7 @@ import path from 'path';import { ManualPromise } from '@isomorphic/manualPromise';import { wrapInASCIIBox } from '@utils/ascii';+import { isChromiumChannelName, defaultUserDataDirForChannel } from '@utils/chromiumChannels';import { RecentLogsCollector } from '@utils/debugLogger';import { removeFolders } from '@utils/fileUtils';import { gracefullyCloseSet } from '@utils/processLauncher';@@ -94,7 +95,7 @@ export class Chromium extends BrowserType {else if (headersMap && !Object.keys(headersMap).some(key => key.toLowerCase() === 'user-agent'))headersMap['User-Agent'] = getUserAgent();- const channel = channelToUserDataDir.has(endpointURL) ? endpointURL : undefined;+ const channel = isChromiumChannelName(endpointURL) ? endpointURL : undefined;if (channel)endpointURL = await resolveChannelEndpoint(progress, endpointURL);@@ -467,8 +468,7 @@ async function urlToWSEndpoint(progress: Progress, endpointURL: string, headers:}async function resolveChannelEndpoint(progress: Progress, channel: string): Promise<string> {- const dirs = channelToUserDataDir.get(channel)!;- const userDataDir = dirs[process.platform];+ const userDataDir = defaultUserDataDirForChannel(channel);if (!userDataDir)throw new Error(`Connecting to ${channel} by channel name is not supported on ${process.platform}.`);@@ -535,46 +535,3 @@ function remoteDebuggingHint(channel: string): string {and check "Allow remote debugging for this browser instance".`;}--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/channelSessions.ts b/packages/playwright-core/src/tools/cli-client/channelSessions.tsindex 554984c667..9c222f2123 100644--- a/packages/playwright-core/src/tools/cli-client/channelSessions.ts+++ b/packages/playwright-core/src/tools/cli-client/channelSessions.ts@@ -19,7 +19,7 @@ import net from 'net';import os from 'os';import path from 'path';-import { playwrightExtensionId } from '../utils/extension';+import { isPlaywrightExtensionInstalled } from '../utils/extension';export type ChannelSession = {channel: string;@@ -40,17 +40,13 @@ export async function listChannelSessions(): Promise<ChannelSession[]> {continue;const [endpoint, extensionInstalled] = await Promise.all([readEndpoint(userDataDir),- hasPlaywrightExtension(userDataDir),+ isPlaywrightExtensionInstalled(userDataDir),]);result.push({ channel, userDataDir, endpoint, extensionInstalled });}return result;}-async function hasPlaywrightExtension(userDataDir: string): Promise<boolean> {- return await pathExists(path.join(userDataDir, 'Default', 'Extensions', playwrightExtensionId));-}-async function pathExists(p: string): Promise<boolean> {try {await fs.promises.access(p);@@ -88,8 +84,7 @@ async function isPortOpen(port: number): Promise<boolean> {});}-// Keep in sync with channelToUserDataDir in-// packages/playwright-core/src/server/chromium/chromium.ts.+// Keep in sync with packages/utils/chromiumChannels.ts.const channelToUserDataDir = new Map<string, Record<string, string>>([['chrome', {'linux': path.join(os.homedir(), '.config', 'google-chrome'),diff --git a/packages/playwright-core/src/tools/mcp/extensionContextFactory.ts b/packages/playwright-core/src/tools/mcp/extensionContextFactory.tsindex 579a665b19..cf78af1bc5 100644--- a/packages/playwright-core/src/tools/mcp/extensionContextFactory.ts+++ b/packages/playwright-core/src/tools/mcp/extensionContextFactory.ts@@ -16,7 +16,9 @@import debug from 'debug';import { createHttpServer, startHttpServer } from '@utils/network';+import { defaultUserDataDirForChannel } from '@utils/chromiumChannels';import { playwright } from '../../inprocess';+import { isPlaywrightExtensionInstalled, playwrightExtensionInstallUrl } from '../utils/extension';import { CDPRelayServer } from './cdpRelay';import type * as playwrightTypes from '../../..';@@ -25,11 +27,16 @@ import type { FullConfig } from './config';const debugLogger = debug('pw:mcp:relay');export async function createExtensionBrowser(config: FullConfig, clientName: string): Promise<playwrightTypes.Browser> {+ const channel = config.browser.launchOptions.channel || 'chrome';+ const userDataDir = config.browser.userDataDir ?? defaultUserDataDirForChannel(channel);+ if (userDataDir && !await isPlaywrightExtensionInstalled(userDataDir))+ throw new Error(`Playwright Extension not found in "${userDataDir}". Install it from ${playwrightExtensionInstallUrl}`);+const httpServer = createHttpServer();await startHttpServer(httpServer, {});const relay = new CDPRelayServer(httpServer,- config.browser.launchOptions.channel || 'chrome',+ channel,config.browser.userDataDir,config.browser.launchOptions.executablePath);debugLogger(`CDP relay server started, extension endpoint: ${relay.extensionEndpoint()}.`);diff --git a/packages/playwright-core/src/tools/utils/extension.ts b/packages/playwright-core/src/tools/utils/extension.tsindex 9446b9541d..5ed49da6a5 100644--- a/packages/playwright-core/src/tools/utils/extension.ts+++ b/packages/playwright-core/src/tools/utils/extension.ts@@ -14,7 +14,32 @@* limitations under the License.*/+import fs from 'fs';+import path from 'path';+// Also pinned via the "key" field in packages/extension/manifest.json.export const playwrightExtensionId = 'mmlmfjhmonkocbjadbfplnigmagldckm';export const playwrightExtensionInstallUrl = `https://chromewebstore.google.com/detail/playwright-mcp-bridge/${playwrightExtensionId}`;++export async function isPlaywrightExtensionInstalled(userDataDir: string): Promise<boolean> {+ // Covers two install shapes: web store drops the extension into Default/Extensions/<id>;+ // `--load-extension` does not, and only shows up as the id inside Default/Preferences.+ if (await pathExists(path.join(userDataDir, 'Default', 'Extensions', playwrightExtensionId)))+ return true;+ try {+ const prefs = await fs.promises.readFile(path.join(userDataDir, 'Default', 'Preferences'), 'utf-8');+ return prefs.includes(`"${playwrightExtensionId}"`);+ } catch {+ return false;+ }+}++async function pathExists(p: string): Promise<boolean> {+ try {+ await fs.promises.access(p);+ return true;+ } catch {+ return false;+ }+}diff --git a/packages/utils/chromiumChannels.ts b/packages/utils/chromiumChannels.tsnew file mode 100644index 0000000000..789f472b74--- /dev/null+++ b/packages/utils/chromiumChannels.ts@@ -0,0 +1,69 @@+/**+ * 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 os from 'os';+import path from 'path';++export function defaultUserDataDirForChannel(channel: string): string | undefined {+ return channelToDefaultUserDataDir.get(channel)?.[process.platform];+}++export function isChromiumChannelName(channel: string): boolean {+ return channelToDefaultUserDataDir.has(channel);+}++const channelToDefaultUserDataDir = 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/utils/index.ts b/packages/utils/index.tsindex 42d4a24308..00fd5ca902 100644--- a/packages/utils/index.ts+++ b/packages/utils/index.ts@@ -15,6 +15,7 @@*/export * from './ascii';+export * from './chromiumChannels';export * from './comparators';export * from './crypto';export * from './debug';diff --git a/tests/extension/extension-fixtures.ts b/tests/extension/extension-fixtures.tsindex efe9749a08..6837cb9797 100644--- a/tests/extension/extension-fixtures.ts+++ b/tests/extension/extension-fixtures.ts@@ -79,6 +79,9 @@ export const test = base.extend<TestFixtures, WorkerFixtures & ExtensionTestOptilet browserContext: BrowserContext | undefined;const userDataDir = testInfo.outputPath('extension-user-data-dir');+ // --load-extension does not populate Default/Extensions/<id>; create the folder+ // so the relay's extension-installed check recognizes the test profile.+ await fs.mkdir(path.join(userDataDir, 'Default', 'Extensions', extensionId), { recursive: true });await use({userDataDir,launch: async (mode?: 'disable-extension') => {diff --git a/tests/extension/extension.spec.ts b/tests/extension/extension.spec.tsindex 13d895bcb3..48faa26fb7 100644--- a/tests/extension/extension.spec.ts+++ b/tests/extension/extension.spec.ts@@ -255,6 +255,25 @@ test(`custom executablePath`, async ({ startClient, server }) => {}).toPass();});+test(`fails when extension is missing in custom userDataDir`, async ({ startClient, server }) => {+ const userDataDir = test.info().outputPath('empty-profile');++ const { client } = await startClient({+ args: [`--extension`],+ config: {+ browser: { userDataDir },+ },+ });++ expect(await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.HELLO_WORLD },+ })).toHaveResponse({+ error: expect.stringContaining(`Playwright Extension not found in "${userDataDir}"`),+ isError: true,+ });+});+test(`bypass connection dialog with token`, async ({ browserWithExtension, startClient, server }) => {const browserContext = await browserWithExtension.launch();