Skip to content

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

chore(mcp): add tests for init-page + init-script (#38309)

Pavel Feldman4f42f245d3d1
diff --git a/packages/playwright/src/mcp/browser/config.ts b/packages/playwright/src/mcp/browser/config.ts
index 551c2b7748..72c3937bc8 100644
--- a/packages/playwright/src/mcp/browser/config.ts
+++ b/packages/playwright/src/mcp/browser/config.ts
@@ -132,6 +132,12 @@ async function validateConfig(config: FullConfig): Promise<void> {
throw new Error(`Init script file does not exist: ${script}`);
}
}
+ if (config.browser.initPage) {
+ for (const page of config.browser.initPage) {
+ if (!await fileExistsAsync(page))
+ throw new Error(`Init page file does not exist: ${page}`);
+ }
+ }
if (config.sharedBrowserContext && config.saveVideo)
throw new Error('saveVideo is not supported when sharedBrowserContext is true');
}
diff --git a/packages/playwright/src/mcp/browser/context.ts b/packages/playwright/src/mcp/browser/context.ts
index f3d9208d03..657194f8e9 100644
--- a/packages/playwright/src/mcp/browser/context.ts
+++ b/packages/playwright/src/mcp/browser/context.ts
@@ -90,7 +90,6 @@ export class Context {
const { browserContext } = await this._ensureBrowserContext();
const page = await browserContext.newPage();
this._currentTab = this._tabs.find(t => t.page === page)!;
- await this._currentTab.initializedPromise;
return this._currentTab;
}
diff --git a/packages/playwright/src/mcp/browser/tab.ts b/packages/playwright/src/mcp/browser/tab.ts
index 9613112d88..6bf802c0a0 100644
--- a/packages/playwright/src/mcp/browser/tab.ts
+++ b/packages/playwright/src/mcp/browser/tab.ts
@@ -57,7 +57,8 @@ export class Tab extends EventEmitter<TabEventsInterface> {
private _onPageClose: (tab: Tab) => void;
private _modalStates: ModalState[] = [];
private _downloads: { download: playwright.Download, finished: boolean, outputFile: string }[] = [];
- readonly initializedPromise: Promise<void>;
+ // TODO: split into Tab and TabHeader
+ private _initializedPromise: Promise<void>;
private _needsFullSnapshot = false;
constructor(context: Context, page: playwright.Page, onPageClose: (tab: Tab) => void) {
@@ -84,7 +85,7 @@ export class Tab extends EventEmitter<TabEventsInterface> {
page.setDefaultNavigationTimeout(this.context.config.timeouts.navigation);
page.setDefaultTimeout(this.context.config.timeouts.action);
(page as any)[tabSymbol] = this;
- this.initializedPromise = this._initialize();
+ this._initializedPromise = this._initialize();
}
static forPage(page: playwright.Page): Tab | undefined {
@@ -186,10 +187,12 @@ export class Tab extends EventEmitter<TabEventsInterface> {
}
async waitForLoadState(state: 'load', options?: { timeout?: number }): Promise<void> {
+ await this._initializedPromise;
await callOnPageNoTrace(this.page, page => page.waitForLoadState(state, options).catch(logUnhandledError));
}
async navigate(url: string) {
+ await this._initializedPromise;
this._clearCollectedArtifacts();
const downloadEvent = callOnPageNoTrace(this.page, page => page.waitForEvent('download').catch(logUnhandledError));
@@ -219,16 +222,17 @@ export class Tab extends EventEmitter<TabEventsInterface> {
}
async consoleMessages(type?: 'error'): Promise<ConsoleMessage[]> {
- await this.initializedPromise;
+ await this._initializedPromise;
return this._consoleMessages.filter(message => type ? message.type === type : true);
}
async requests(): Promise<Set<playwright.Request>> {
- await this.initializedPromise;
+ await this._initializedPromise;
return this._requests;
}
async captureSnapshot(): Promise<TabSnapshot> {
+ await this._initializedPromise;
let tabSnapshot: TabSnapshot | undefined;
const modalStates = await this._raceAgainstModalStates(async () => {
const snapshot = await this.page._snapshotForAI({ track: 'response' });
@@ -282,14 +286,17 @@ export class Tab extends EventEmitter<TabEventsInterface> {
}
async waitForCompletion(callback: () => Promise<void>) {
+ await this._initializedPromise;
await this._raceAgainstModalStates(() => waitForCompletion(this, callback));
}
async refLocator(params: { element: string, ref: string }): Promise<{ locator: Locator, resolved: string }> {
+ await this._initializedPromise;
return (await this.refLocators([params]))[0];
}
async refLocators(params: { element: string, ref: string }[]): Promise<{ locator: Locator, resolved: string }[]> {
+ await this._initializedPromise;
return Promise.all(params.map(async param => {
try {
const locator = this.page.locator(`aria-ref=${param.ref}`).describe(param.element) as Locator;
diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.ts
index d71a5b80bb..5f1d98514b 100644
--- a/packages/playwright/src/mcp/program.ts
+++ b/packages/playwright/src/mcp/program.ts
@@ -36,7 +36,7 @@ export function decorateCommand(command: Command, version: string) {
command
.option('--allowed-hosts <hosts...>', 'comma-separated list of hosts this server is allowed to serve from. Defaults to the host the server is bound to. Pass \'*\' to disable the host check.', commaSeparatedList)
.option('--allowed-origins <origins>', 'semicolon-separated list of TRUSTED origins to allow the browser to request. Default is to allow all.\nImportant: *does not* serve as a security boundary and *does not* affect redirects. ', semicolonSeparatedList)
- .option('--blocked-origins <origins>', 'semicolon-separated list of TRUSTED origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.\nImportant: *does not* serve as a security boundary and *does not* affect redirects.', semicolonSeparatedList)
+ .option('--blocked-origins <origins>', 'semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.\nImportant: *does not* serve as a security boundary and *does not* affect redirects.', semicolonSeparatedList)
.option('--block-service-workers', 'block service workers')
.option('--browser <browser>', 'browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.')
.option('--caps <caps>', 'comma-separated list of additional capabilities to enable, possible values: vision, pdf.', commaSeparatedList)
diff --git a/tests/mcp/init-page.spec.ts b/tests/mcp/init-page.spec.ts
index 95013b364d..ad363f7212 100644
--- a/tests/mcp/init-page.spec.ts
+++ b/tests/mcp/init-page.spec.ts
@@ -30,8 +30,48 @@ test('--init-page', async ({ startClient }) => {
});
expect(await client.callTool({
name: 'browser_snapshot',
- arguments: { url: 'about:blank' },
+ arguments: {},
})).toHaveResponse({
pageState: expect.stringContaining('Hello world'),
});
});
+
+test('--init-page w/ --init-script', async ({ startClient, server }) => {
+ server.setContent('/', `
+ <div>Hello world</div>
+ `, 'text/html');
+
+ const initPagePath = test.info().outputPath('initPage.ts');
+ await fs.promises.writeFile(initPagePath, `
+ export default async ({ page }) => {
+ await page.context().grantPermissions(['geolocation']);
+ await page.context().setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
+ };
+ `);
+ const initScriptPath = test.info().outputPath('initScript.js');
+ await fs.promises.writeFile(initScriptPath, `
+ const options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 };
+ function success(pos) { console.log(pos.coords.latitude, pos.coords.longitude); }
+ function error(error) { console.error(error); }
+ navigator.geolocation.getCurrentPosition(success, error, options);
+ `);
+
+ const { client } = await startClient({
+ args: [`--init-page=${initPagePath}`, `--init-script=${initScriptPath}`],
+ });
+ expect(await client.callTool({
+ name: 'browser_navigate',
+ arguments: {
+ url: server.PREFIX,
+ },
+ })).toHaveResponse({
+ pageState: expect.stringContaining('Hello world'),
+ });
+
+ expect(await client.callTool({
+ name: 'browser_console_messages',
+ arguments: {},
+ })).toHaveResponse({
+ result: expect.stringContaining('37.7749 -122.4194'),
+ });
+});