### Install the browser specified in the config Source: https://github.com/microsoft/playwright-mcp Install the browser specified in the config. Call this if you get an error about the browser not being installed. ```APIDOC browser_install() Description: Install the browser specified in the config. Call this if you get an error about the browser not being installed. Parameters: None Read-only: false ``` -------------------------------- ### Install the browser specified in the config Source: https://github.com/microsoft/playwright-mcp Install the browser specified in the config. Call this if you get an error about the browser not being installed. ```APIDOC browser_install() ``` -------------------------------- ### Playwright Component Testing Examples for React, Vue, and Svelte Source: https://playwright.dev/docs/test-components These examples illustrate how to perform basic component testing using Playwright's experimental component testing libraries for React, Vue, and Svelte. Each example demonstrates setting a viewport, mounting a `HelloWorld` component, and asserting its text content, highlighting the framework-specific `mount` syntax. ```JavaScript import { test, expect } from '@playwright/experimental-ct-react'; import HelloWorld from './HelloWorld'; test.use({ viewport: { width: 500, height: 500 } }); test('should work', async ({ mount }) => { const component = await mount(); await expect(component).toContainText('Greetings'); }); ``` ```JavaScript import { test, expect } from '@playwright/experimental-ct-vue'; import HelloWorld from './HelloWorld.vue'; test.use({ viewport: { width: 500, height: 500 } }); test('should work', async ({ mount }) => { const component = await mount(HelloWorld, { props: { msg: 'Greetings', }, }); await expect(component).toContainText('Greetings'); }); ``` ```JavaScript import { test, expect } from '@playwright/experimental-ct-svelte'; import HelloWorld from './HelloWorld.svelte'; test.use({ viewport: { width: 500, height: 500 } }); test('should work', async ({ mount }) => { const component = await mount(HelloWorld, { props: { msg: 'Greetings', }, }); await expect(component).toContainText('Greetings'); }); ``` -------------------------------- ### Run TodoMVC Example with Cloudflare Wrangler Source: https://github.com/cloudflare/playwright This snippet provides commands to run the TodoMVC example using Cloudflare Wrangler. It navigates to the example directory, installs dependencies, and starts the development server remotely, allowing the user to open the browser. ```shell cd packages/playwright-cloudflare/examples/todomvc npm ci npx wrangler dev --remote ``` -------------------------------- ### Programmatic Playwright MCP Server Setup with SSE Transport Source: https://github.com/microsoft/playwright-mcp JavaScript example demonstrating how to programmatically create a headless Playwright MCP server connection and set up an SSE transport for communication, integrating with an HTTP server. ```JavaScript import http from 'http'; import { createConnection } from '@playwright/mcp'; import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'; http.createServer(async (req, res) => { // ... // Creates a headless Playwright MCP server with SSE transport const connection = await createConnection({ browser: { launchOptions: { headless: true } } }); const transport = new SSEServerTransport('/messages', res); await connection.sever.connect(transport); // ... }); ``` -------------------------------- ### React Component Test Example with Playwright Source: https://playwright.dev/docs/test-components An example test file (`src/App.spec.tsx`) demonstrating how to mount a React component and assert its text content using Playwright's experimental component testing for React. ```TypeScript import { test, expect } from '@playwright/experimental-ct-react'; import App from './App'; test('should work', async ({ mount }) => { const component = await mount(); await expect(component).toContainText('Learn React'); }); ``` -------------------------------- ### Install Playwright MCP Server via VS Code CLI Source: https://github.com/microsoft/playwright-mcp This shell command demonstrates how to install the Playwright MCP server using the VS Code command-line interface. It adds a new MCP server configuration named 'playwright' that executes 'npx @playwright/mcp@latest'. ```Shell # For VS Code code --add-mcp '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}' ``` -------------------------------- ### Install Node.js Dependencies for Puppeteer Examples Source: https://github.com/cloudflare/puppeteer/tree/main/examples This command installs all necessary Node.js packages and dependencies required to run the Puppeteer examples. It should be executed in the root directory of the Puppeteer repository after cloning to ensure all project requirements are met. ```Shell npm install ``` -------------------------------- ### Configure Playwright MCP Server in Claude Desktop Source: https://github.com/microsoft/playwright-mcp For installing the Playwright Model Context Protocol (MCP) server in Claude Desktop, refer to the general MCP installation guide and use the specified JSON configuration. This configuration sets up the 'playwright' MCP server, instructing it to use 'npx' with '@playwright/mcp@latest' as its argument. ```json { "mcpServers": { "playwright": { "command": "npx", "args": [ "@playwright/mcp@latest" ] } } } ``` -------------------------------- ### Svelte Component Test Example with Playwright Source: https://playwright.dev/docs/test-components An example test file (`src/App.spec.ts`) demonstrating how to mount a Svelte component and assert its text content using Playwright's experimental component testing for Svelte. ```TypeScript import { test, expect } from '@playwright/experimental-ct-svelte'; import App from './App.svelte'; test('should work', async ({ mount }) => { const component = await mount(App); await expect(component).toContainText('Learn Svelte'); }); ``` -------------------------------- ### Run TodoMVC Example with Cloudflare Playwright Source: https://github.com/cloudflare/playwright Commands to run the TodoMVC example using Cloudflare Playwright. This involves navigating to the example directory, installing dependencies, and launching the application with `wrangler dev --remote` to open it in a browser. ```Shell cd packages/playwright-cloudflare/examples/todomvc npm ci npx wrangler dev --remote ``` -------------------------------- ### Configure Playwright MCP Server via JSON Source: https://github.com/microsoft/playwright-mcp This JSON configuration block defines the setup for the Playwright Model Context Protocol (MCP) server. It specifies 'playwright' as the server name, 'npx' as the command, and '@playwright/mcp@latest' as the arguments to install the latest Playwright MCP. This configuration is used across various IDEs and clients. ```JSON { "mcpServers": { "playwright": { "command": "npx", "args": [ "@playwright/mcp@latest" ] } } } ``` -------------------------------- ### Run TodoMVC Example with Wrangler Dev Source: https://www.npmjs.com/package/@cloudflare/playwright This sequence of bash commands demonstrates how to run the TodoMVC example application using Cloudflare's 'wrangler dev' tool. It includes navigating to the example directory, installing dependencies, and launching the development server remotely. ```bash cd packages/playwright-cloudflare/examples/todomvc npm ci npx wrangler dev --remote ``` -------------------------------- ### Go back Source: https://github.com/microsoft/playwright-mcp Go back to the previous page ```APIDOC browser_navigate_back: Title: Go back Description: Go back to the previous page Parameters: None Read-only: true ``` -------------------------------- ### Navigate to a URL Source: https://github.com/microsoft/playwright-mcp Navigate to a URL ```APIDOC browser_navigate: Title: Navigate to a URL Description: Navigate to a URL Parameters: url (string): The URL to navigate to Read-only: false ``` -------------------------------- ### Install Playwright MCP for VS Code Source: https://github.com/microsoft/playwright-mcp This shell command adds the Playwright MCP server configuration to VS Code, allowing it to be used with GitHub Copilot. It specifies the server name as 'playwright' and the command to run as 'npx @playwright/mcp@latest'. ```Shell # For VS Code code --add-mcp '{\"name\":\"playwright\",\"command\":\"npx\",\"args\":[\"@playwright/mcp@latest\"]}' ``` -------------------------------- ### Select a tab Source: https://github.com/microsoft/playwright-mcp Select a tab by index ```APIDOC browser_tab_select(index: number) Description: Select a tab by index Parameters: index: The index of the tab to select Read-only: true ``` -------------------------------- ### Run Playwright MCP Server with Configuration File Source: https://github.com/microsoft/playwright-mcp Command to start the Playwright MCP server, specifying a custom JSON configuration file using the `--config` option for tailored behavior. ```Shell npx @playwright/mcp@latest --config path/to/config.json ``` -------------------------------- ### Test Component Interaction with Playwright Source: https://playwright.dev/docs/test-components Demonstrates how to mount a component, assert its content, simulate a click event, and verify event firing using Playwright's component testing API. This example tests a Button component's click functionality. ```JavaScript test('event should work', async ({ mount }) => { let clicked = false; // Mount a component. Returns locator pointing to the component. const component = await mount( ); // As with any Playwright test, assert locator text. await expect(component).toContainText('Submit'); // Perform locator click. This will trigger the event. await component.click(); // Assert that respective events have been fired. expect(clicked).toBeTruthy(); }); ``` -------------------------------- ### Go forward Source: https://github.com/microsoft/playwright-mcp Go forward to the next page -------------------------------- ### Install Playwright MCP Server using VS Code CLI Source: https://github.com/microsoft/playwright-mcp This shell command uses the VS Code CLI to add the Playwright Model Context Protocol (MCP) server. It directly injects the necessary configuration, specifying the server name, command, and arguments for installation within the VS Code environment. ```Shell code --add-mcp '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}' ``` -------------------------------- ### Handle a dialog Source: https://github.com/microsoft/playwright-mcp Handle a dialog ```APIDOC browser_handle_dialog: Title: Handle a dialog Description: Handle a dialog Parameters: accept (boolean): Whether to accept the dialog. promptText (string, optional): The text of the prompt in case of a prompt dialog. Read-only: false ``` -------------------------------- ### Configuring Playwright Component Tests with Hooks Source: https://playwright.dev/docs/test-components This section details the use of `beforeMount` and `afterMount` hooks in Playwright component testing for advanced setup, such as configuring routers or mock servers. It also shows how to pass custom configuration from a test via the `hooksConfig` fixture. Examples are provided for both React and Vue, demonstrating how to enable routing before a component is mounted. ```React import { beforeMount, afterMount } from '@playwright/experimental-ct-react/hooks'; import { BrowserRouter } from 'react-router-dom'; export type HooksConfig = { enableRouting?: boolean; } beforeMount(async ({ App, hooksConfig }) => { if (hooksConfig?.enableRouting) return ; }); ``` ```React import { test, expect } from '@playwright/experimental-ct-react'; import type { HooksConfig } from '../playwright'; import { ProductsPage } from './pages/ProductsPage'; test('configure routing through hooks config', async ({ page, mount }) => { const component = await mount(, { hooksConfig: { enableRouting: true } }); await expect(component.getByRole('link')).toHaveAttribute('href', '/products/42'); }); ``` ```Vue import { beforeMount, afterMount } from '@playwright/experimental-ct-vue/hooks'; import { router } from '../src/router'; export type HooksConfig = { enableRouting?: boolean; } beforeMount(async ({ app, hooksConfig }) => { if (hooksConfig?.enableRouting) app.use(router); }); ``` ```Vue import { test, expect } from '@playwright/experimental-ct-vue'; import type { HooksConfig } from '../playwright'; import ProductsPage from './pages/ProductsPage.vue'; test('configure routing through hooks config', async ({ page, mount }) => { const component = await mount(ProductsPage, { hooksConfig: { enableRouting: true } }); await expect(component.getByRole('link')).toHaveAttribute('href', '/products/42'); }); ``` -------------------------------- ### Vue Component Test Examples with Playwright Source: https://playwright.dev/docs/test-components Example test files for Vue components using Playwright's experimental component testing. These examples show how to mount a Vue component and assert its text content, covering both `.ts` and `.tsx` test file extensions. ```TypeScript import { test, expect } from '@playwright/experimental-ct-vue'; import App from './App.vue'; test('should work', async ({ mount }) => { const component = await mount(App); await expect(component).toContainText('Learn Vue'); }); ``` ```TypeScript import { test, expect } from '@playwright/experimental-ct-vue'; import App from './App.vue'; test('should work', async ({ mount }) => { const component = await mount(); await expect(component).toContainText('Learn Vue'); }); ``` -------------------------------- ### Take a screenshot Source: https://github.com/microsoft/playwright-mcp Take a screenshot of the current page ```APIDOC browser_screen_capture() Description: Take a screenshot of the current page Parameters: None Read-only: true ``` -------------------------------- ### Install Playwright MCP Server using Claude Code CLI Source: https://github.com/microsoft/playwright-mcp This shell command utilizes the Claude Code CLI to add the Playwright Model Context Protocol (MCP) server. It provides a concise way to register the server with the Claude Code environment, specifying the server name and the npx command for installation. ```Shell claude mcp add playwright npx @playwright/mcp@latest ``` -------------------------------- ### Configure Playwright MCP in Cursor Settings Source: https://github.com/microsoft/playwright-mcp This JSON configuration snippet defines the 'playwright' MCP server within Cursor's settings. It specifies 'npx' as the command and '@playwright/mcp@latest' as its argument, enabling manual setup of the Playwright MCP server. ```JSON { \"mcpServers\": { \"playwright\": { \"command\": \"npx\", \"args\": [ \"@playwright/mcp@latest\" ] } } } ``` -------------------------------- ### Open a new tab Source: https://github.com/microsoft/playwright-mcp Open a new tab ```APIDOC browser_tab_new(url: string (optional)) Description: Open a new tab Parameters: url: The URL to navigate to in the new tab. If not provided, the new tab will be blank. Read-only: true ``` -------------------------------- ### List tabs Source: https://github.com/microsoft/playwright-mcp List browser tabs ```APIDOC browser_tab_list() Description: List browser tabs Parameters: None Read-only: true ``` -------------------------------- ### Click Source: https://github.com/microsoft/playwright-mcp Click left mouse button ```APIDOC browser_screen_click(element: string, x: number, y: number) Description: Click left mouse button Parameters: element: Human-readable element description used to obtain permission to interact with the element x: X coordinate y: Y coordinate Read-only: false ``` -------------------------------- ### Browser Automation Configuration Interface Source: https://github.com/microsoft/playwright-mcp This API documentation outlines the configurable properties for a browser automation setup. It includes options for user data directory persistence, Playwright launch and context settings, CDP and remote Playwright endpoints, server configuration, and a list of supported capabilities such as core automation, tab management, PDF generation, and history. ```APIDOC // Path to user data directory for browser profile persistence userDataDir?: string; // Browser launch options (see Playwright docs) // @see https://playwright.dev/docs/api/class-browsertype#browser-type-launch launchOptions?: { channel?: string; // Browser channel (e.g. 'chrome') headless?: boolean; // Run in headless mode executablePath?: string; // Path to browser executable // ... other Playwright launch options }; // Browser context options // @see https://playwright.dev/docs/api/class-browser#browser-new-context contextOptions?: { viewport?: { width: number, height: number }; // ... other Playwright context options }; // CDP endpoint for connecting to existing browser cdpEndpoint?: string; // Remote Playwright server endpoint remoteEndpoint?: string; }, // Server configuration server?: { port?: number; // Port to listen on host?: string; // Host to bind to (default: localhost) }, // List of enabled capabilities capabilities?: Array< 'core' | // Core browser automation 'tabs' | // Tab management 'pdf' | // PDF generation 'history' | ``` -------------------------------- ### Click mouse Source: https://github.com/microsoft/playwright-mcp Click left mouse button. ```APIDOC browser_screen_click: Description: Click left mouse button Parameters: element (string): Human-readable element description used to obtain permission to interact with the element x (number): X coordinate y (number): Y coordinate Read-only: false ``` -------------------------------- ### List tabs Source: https://github.com/microsoft/playwright-mcp List browser tabs. ```APIDOC browser_tab_list() ``` -------------------------------- ### Comprehensive Playwright Electron Automation Example Source: https://playwright.dev/docs/api/class-electron This example showcases a full workflow for automating an Electron application using Playwright. It includes launching the app, evaluating code in the main process, interacting with the first window (getting title, taking screenshot, handling console events, clicking elements), and gracefully closing the application. ```javascript const { _electron: electron } = require('playwright');(async () => { // Launch Electron app. const electronApp = await electron.launch({ args: ['main.js'] }); // Evaluation expression in the Electron context. const appPath = await electronApp.evaluate(async ({ app }) => { // This runs in the main Electron process, parameter here is always // the result of the require('electron') in the main app script. return app.getAppPath(); }); console.log(appPath); // Get the first window that the app opens, wait if necessary. const window = await electronApp.firstWindow(); // Print the title. console.log(await window.title()); // Capture a screenshot. await window.screenshot({ path: 'intro.png' }); // Direct Electron console to Node terminal. window.on('console', console.log); // Click button. await window.click('text=Click me'); // Exit app. await electronApp.close();})(); ``` -------------------------------- ### Resize browser window Source: https://github.com/microsoft/playwright-mcp Resize the browser window ```APIDOC browser_resize(width: number, height: number) Description: Resize the browser window Parameters: width: Width of the browser window height: Height of the browser window Read-only: true ``` -------------------------------- ### Generate a Playwright test Source: https://github.com/microsoft/playwright-mcp Generate a Playwright test for given scenario ```APIDOC browser_generate_playwright_test(name: string, description: string, steps: array) Description: Generate a Playwright test for given scenario Parameters: name: The name of the test description: The description of the test steps: The steps of the test Read-only: true ``` -------------------------------- ### Playwright Component Test HTML Root Template Source: https://playwright.dev/docs/test-components The `playwright/index.html` file defines the HTML structure used by Playwright to render components during testing. It must contain an element with `id="root"` for component mounting and link to a script for setup. ```HTML
``` -------------------------------- ### Example HTTP Request with Message Signature Headers Source: https://datatracker.ietf.org/doc/html/draft-meunier-web-bot-auth-architecture This example demonstrates how an Agent sends an HTTP GET request including the `Signature`, `Signature-Input`, and `Signature-Agent` headers. The `Signature-Input` header specifies the signed components, creation/expiration timestamps, key ID, and an optional tag, while `Signature-Agent` indicates the signer's URL. ```APIDOC GET /path/to/resource Signature: abc== Signature-Input: sig=(@authority signature-agent);\\ created=1700000000;\\ expires=1700011111;\\ keyid="ba3e64==";\\ tag="web-bot-auth" Signature-Agent: "https://signer.example.com" ``` -------------------------------- ### Execute a Specific Puppeteer Example Script Source: https://github.com/cloudflare/puppeteer/tree/main/examples This command runs the `search.js` example script located in the `examples` directory. The `NODE_PATH=../` prefix is crucial as it configures Node.js to resolve modules from the parent directory, allowing the example to correctly import the Puppeteer library. ```Shell NODE_PATH=../ node examples/search.js ``` -------------------------------- ### Build Playwright MCP Docker Image Source: https://github.com/microsoft/playwright-mcp Command to build a custom Docker image for the Playwright MCP server, tagging it with the specified name 'mcr.microsoft.com/playwright/mcp' for local use. ```Shell docker build -t mcr.microsoft.com/playwright/mcp . ``` -------------------------------- ### Override Pinia Store Initial State in Playwright Test Source: https://playwright.dev/docs/test-components This TypeScript test example shows how to override the initial state of a Pinia store for a specific component test. By passing `hooksConfig` to the `mount` function, the `initialState` defined in the Pinia setup (as shown in the `playwright/index.ts` example) can be dynamically set for each test, allowing for isolated state testing. ```TypeScript import { test, expect } from '@playwright/experimental-ct-vue';import type { HooksConfig } from '../playwright';import Store from './Store.vue';test('override initialState ', async ({ mount }) => { const component = await mount(Store, { hooksConfig: { store: { name: 'override initialState' } } }); await expect(component).toContainText('override initialState');}); ``` -------------------------------- ### Electron Launch Method Usage Examples Source: https://playwright.dev/docs/api/class-electron Basic usage examples for the `electron.launch` method, showing how to launch an Electron application with and without an options object. This demonstrates the fundamental syntax for invoking the launch function. ```JavaScript await electron.launch(); ``` ```JavaScript await electron.launch(options); ``` -------------------------------- ### Install Project Dependencies with npm Source: https://github.com/cloudflare/playwright-mcp/blob/main/cloudflare/example/README This command installs all project dependencies as specified in the package-lock.json file, ensuring a clean and reproducible build. ```Shell npm ci ``` -------------------------------- ### Playwright Component Test: InputMediaForTest.spec.tsx Source: https://playwright.dev/docs/test-components Provides an example of a Playwright test for the `InputMediaForTest` story component. It demonstrates how to mount the story, simulate user interaction (setting input files), and assert the outcome by checking the simplified `mediaSelected` string. ```TypeScript import { test, expect } from '@playwright/experimental-ct-react'; import { InputMediaForTest } from './input-media.story.tsx'; test('changes the image', async ({ mount }) => { let mediaSelected: string | null = null; const component = await mount( { mediaSelected = mediaName; }} /> ); await component .getByTestId('imageInput') .setInputFiles('src/assets/logo.png'); await expect(component.getByAltText(/selected image/i)).toBeVisible(); await expect.poll(() => mediaSelected).toBe('logo.png'); }); ``` -------------------------------- ### Get console messages Source: https://github.com/microsoft/playwright-mcp Returns all console messages ```APIDOC browser_console_messages() Description: Returns all console messages Parameters: None Read-only: true ``` -------------------------------- ### Get console messages Source: https://github.com/microsoft/playwright-mcp Returns all console messages. ```APIDOC browser_console_messages() ``` -------------------------------- ### Example: Select and Click Element with Puppeteer Source: https://github.com/cloudflare/puppeteer/blob/main/docs/api/index This TypeScript example demonstrates how to launch a Puppeteer browser, navigate to a page, select an anchor element using `page.$()`, and then click on it using an `ElementHandle`. ```TypeScript import puppeteer from 'puppeteer'; (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); const hrefElement = await page.$('a'); await hrefElement.click(); // ... })(); ``` -------------------------------- ### Playwright MCP CLI Arguments Reference Source: https://github.com/microsoft/playwright-mcp A complete reference of command-line arguments for `npx @playwright/mcp@latest`, including options for origin control, browser selection, device emulation, proxy configuration, and session management. Each argument's purpose, syntax, and default behavior are described. ```APIDOC > npx @playwright/mcp@latest --help --allowed-origins semicolon-separated list of origins to allow the browser to request. Default is to allow all. --blocked-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. --block-service-workers block service workers --browser browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge. --browser-agent Use browser agent (experimental). --caps comma-separated list of capabilities to enable, possible values: tabs, pdf, history, wait, files, install. Default is all. --cdp-endpoint CDP endpoint to connect to. --config path to the configuration file. --device device to emulate, for example: "iPhone 15" --executable-path path to the browser executable. --headless run browser in headless mode, headed by default --host host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces. --ignore-https-errors ignore https errors --isolated keep the browser profile in memory, do not save it to disk. --image-responses whether to send image responses to the client. Can be "allow", "omit", or "auto". Defaults to "auto", which sends images if the client can display them. --no-sandbox disable the sandbox for all process types that are normally sandboxed. --output-dir path to the directory for output files. --port port to listen on for SSE transport. --proxy-bypass comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com" --proxy-server specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080" --save-trace Whether to save the Playwright Trace of the session into the output directory. --storage-state path to the storage state file for isolated sessions. --user-agent specify user agent string --user-data-dir path to the user data directory. If not specified, a temporary directory will be created. --viewport-size specify browser viewport size in pixels, for example "1280, 720" --vision Run server that uses screenshots (Aria snapshots are used by default) ``` -------------------------------- ### launch(options) API Method Source: https://github.com/cloudflare/puppeteer/blob/main/docs/api/index Launches a new browser instance with Puppeteer. An 'options' object can be passed to configure the browser launch, such as headless mode or arguments. ```APIDOC launch(options) ``` -------------------------------- ### Puppeteer ProductLauncher Class API Source: https://github.com/cloudflare/puppeteer/blob/main/docs/api/index The ProductLauncher class describes a component capable of creating and launching a browser instance. Its constructor is internal, meaning third-party code should not directly call it or extend the class. ```APIDOC ProductLauncher Class: Description: Describes a launcher - a class that is able to create and launch a browser instance. Constructor: The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the ProductLauncher class. ``` -------------------------------- ### React Component Definition: InputMedia.tsx Source: https://playwright.dev/docs/test-components Defines a React component `InputMedia` that accepts a complex `Media` object via its `onChange` prop. This component serves as an example of a component that would typically cause issues when directly tested with Playwright due to the complex object type. ```TypeScript import React from 'react'; type InputMediaProps = { // Media is a complex browser object we can't send to Node while testing. onChange(media: Media): void; }; export function InputMedia(props: InputMediaProps) { return <> as any; } ``` -------------------------------- ### Initialize Pinia for Playwright Component Testing Source: https://playwright.dev/docs/test-components This TypeScript code snippet demonstrates how to initialize Pinia for component testing within Playwright. It uses the `beforeMount` hook to set up `createTestingPinia`, allowing for `initialState` to be configured via `hooksConfig` and disabling action stubbing. It also shows an example of `createSpy`. ```TypeScript import { beforeMount, afterMount } from '@playwright/experimental-ct-vue/hooks';import { createTestingPinia } from '@pinia/testing';import type { StoreState } from 'pinia';import type { useStore } from '../src/store';export type HooksConfig = { store?: StoreState>;}beforeMount(async ({ hooksConfig }) => { createTestingPinia({ initialState: hooksConfig?.store, /** * Use http intercepting to mock api calls instead: * https://playwright.dev/docs/mock#mock-api-requests */ stubActions: false, createSpy(args) { console.log('spy', args) return () => console.log('spy-returns') }, });}); ``` -------------------------------- ### Initialize Playwright Component Testing Source: https://playwright.dev/docs/test-components Commands to initialize Playwright Test for component testing in an existing project, creating necessary configuration files and setting up the environment for different package managers. ```Shell npm init playwright@latest -- --ct ``` ```Shell yarn create playwright --ct ``` ```Shell pnpm create playwright --ct ``` -------------------------------- ### Configure Playwright Component Testing with Vite Plugins and Aliases Source: https://playwright.dev/docs/test-components This advanced configuration demonstrates how to specify Vite plugins and path aliases within Playwright's `ctViteConfig` for component testing. It includes examples of `vue()`, `AutoImport`, and `Components` plugins, along with a custom `@` alias for source directories. ```TypeScript import { defineConfig, devices } from '@playwright/experimental-ct-vue'; import { resolve } from 'path'; import vue from '@vitejs/plugin-vue'; import AutoImport from 'unplugin-auto-import/vite'; import Components from 'unplugin-vue-components/vite'; export default defineConfig({ testDir: './tests/component', use: { trace: 'on-first-retry', ctViteConfig: { plugins: [ vue(), AutoImport({ imports: [ 'vue', 'vue-router', '@vueuse/head', 'pinia', { '@/store': ['useStore'], }, ], dts: 'src/auto-imports.d.ts', eslintrc: { enabled: true, }, }), Components({ dirs: ['src/components'], extensions: ['vue'], }), ], resolve: { alias: { '@': resolve(__dirname, './src'), }, }, }, }, }); ``` -------------------------------- ### Handle Network Requests with Playwright Router Fixture Source: https://playwright.dev/docs/test-components Explains how to intercept and handle network requests in Playwright component tests using the experimental `router` fixture. It covers installing common handlers before each test and introducing one-off handlers for specific tests, often integrating with the MSW library. ```TypeScript import { handlers } from '@src/mocks/handlers'; test.beforeEach(async ({ router }) => { // install common handlers before each test await router.use(...handlers); }); test('example test', async ({ mount }) => { // test as usual, your handlers are active // ... }); ``` ```TypeScript import { http, HttpResponse } from 'msw'; test('example test', async ({ mount, router }) => { await router.use(http.get('/data', async ({ request }) => { return HttpResponse.json({ value: 'mocked' }); })); // test as usual, your handler is active // ... }); ``` -------------------------------- ### Configure Playwright MCP Server in Windsurf Source: https://github.com/microsoft/playwright-mcp To integrate the Playwright Model Context Protocol (MCP) server into Windsurf, follow the official Windsurf MCP documentation and apply the provided JSON configuration. This setup defines the 'playwright' MCP server, specifying 'npx' as the command and '@playwright/mcp@latest' as its argument. ```json { "mcpServers": { "playwright": { "command": "npx", "args": [ "@playwright/mcp@latest" ] } } } ``` -------------------------------- ### Build the Puppeteer Project Source: https://github.com/cloudflare/puppeteer/tree/main/examples This command compiles and builds the Puppeteer project. It's a prerequisite for running the examples, ensuring all necessary artifacts and compiled files are generated before execution. ```Shell npm run build ``` -------------------------------- ### Configure Playwright MCP Server with Direct URL Source: https://github.com/microsoft/playwright-mcp This JSON configuration specifies the URL for connecting to a Playwright Model Context Protocol (MCP) server. It defines a single Playwright server instance accessible via a local SSE endpoint. This setup is suitable for direct connections to a running MCP server. ```JSON { "mcpServers": { "playwright": { "url": "http://localhost:8931/sse" } } } ``` -------------------------------- ### Set Up Local Environment Variables Source: https://context7_llms Illustrates how to create a `.dev.vars` file to securely store sensitive information like `ACCOUNT_ID` and `API_TOKEN` for local development, which are necessary for authenticating with Workers AI services. ```APIDOC ACCOUNT_ID= API_TOKEN= ``` -------------------------------- ### Close a tab Source: https://github.com/microsoft/playwright-mcp Close a tab ```APIDOC browser_tab_close(index: number (optional)) Description: Close a tab Parameters: index: The index of the tab to close. Closes current tab if not provided. Read-only: false ``` -------------------------------- ### Close browser Source: https://github.com/microsoft/playwright-mcp Close the page ```APIDOC browser_close() Description: Close the page Parameters: None Read-only: true ``` -------------------------------- ### Close browser Source: https://github.com/microsoft/playwright-mcp Close the page. ```APIDOC browser_close() ``` -------------------------------- ### Deploy Project to Cloudflare Workers Source: https://www.npmjs.com/package/@cloudflare/playwright-mcp Navigates into the `cloudflare/example` directory and deploys the project to Cloudflare Workers using the Wrangler CLI. ```Shell cd cloudflare/example npx wrangler deploy ``` -------------------------------- ### Automate Browser Interaction with Puppeteer Source: https://github.com/cloudflare/puppeteer/blob/main/docs/api/index This JavaScript snippet demonstrates how to launch a Puppeteer browser, open a new page, navigate to a URL, find an element, and simulate a click. It's a basic example of browser automation. ```JavaScript from 'puppeteer'; (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); const hrefElement = await page.$('a'); await hrefElement.click(); // ... })(); ``` -------------------------------- ### Initialize Cloudflare Worker Project Source: https://context7_llms Uses the `create-cloudflare` CLI to scaffold a new Cloudflare Worker project, specifically configured for browser rendering capabilities. ```sh npm create cloudflare@latest -- browser-worker ``` -------------------------------- ### Playwright MCP Server Command-Line Arguments Reference Source: https://github.com/microsoft/playwright-mcp Detailed reference of all available command-line arguments for configuring the Playwright MCP server. This includes options for controlling browser behavior, network access, security settings, output, and user data management. ```APIDOC --allowed-origins semicolon-separated list of origins to allow the browser to request. Default is to allow all. --blocked-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. --block-service-workers block service workers --browser browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge. --browser-agent Use browser agent (experimental). --caps comma-separated list of capabilities to enable, possible values: tabs, pdf, history, wait, files, install. Default is all. --cdp-endpoint CDP endpoint to connect to. --config path to the configuration file. --device device to emulate, for example: "iPhone 15" --executable-path path to the browser executable. --headless run browser in headless mode, headed by default --host host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces. --ignore-https-errors ignore https errors --isolated keep the browser profile in memory, do not save it to disk. --image-responses whether to send image responses to the client. Can be "allow", "omit", or "auto". Defaults to "auto", which sends images if the client can display them. --no-sandbox disable the sandbox for all process types that are normally sandboxed. --output-dir path to the directory for output files. --port port to listen on for SSE transport. --proxy-bypass comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com" --proxy-server specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080" --save-trace Whether to save the Playwright Trace of the session into the output directory. --storage-state path to the storage state file for isolated sessions. --user-agent specify user agent string --user-data-dir path to the user data directory. If not specified, a temporary directory will be created. --viewport-size specify browser viewport size in pixels, for example "1280, 720" --vision Run server that uses screenshots (Aria snapshots are used by default) ``` -------------------------------- ### Save as PDF Source: https://github.com/microsoft/playwright-mcp Save page as PDF ```APIDOC browser_pdf_save(filename: string (optional)) Description: Save page as PDF Parameters: filename: File name to save the pdf to. Defaults to page-{timestamp}.pdf if not specified. Read-only: true ``` -------------------------------- ### Configure Playwright MCP Server Source: https://github.com/microsoft/playwright-mcp This JSON configuration defines how to set up the Playwright MCP server within a client application. It specifies the 'playwright' server, its command ('npx'), and the arguments required to run the latest Playwright MCP package. ```JavaScript { "mcpServers": { "playwright": { "command": "npx", "args": [ "@playwright/mcp@latest" ] } } } ``` -------------------------------- ### FileChooser Class Documentation Source: https://github.com/cloudflare/puppeteer/blob/main/docs/api/index Provides API documentation for the FileChooser class, which manages file selection requests from a page. It explains how instances are obtained, browser-specific limitations, and internal constructor details. ```APIDOC Class: FileChooser Description: Handles page requests for file selection. Remarks: - Instances obtained via Page.waitForFileChooser(). - Only one file chooser can be open at a time in browsers. - All file choosers must be accepted or canceled to prevent blocking. - Constructor is internal; direct instantiation or subclassing is discouraged. ``` -------------------------------- ### Drag mouse Source: https://github.com/microsoft/playwright-mcp Drag left mouse button ```APIDOC browser_screen_drag(element: string, startX: number, startY: number, endX: number) Description: Drag left mouse button Parameters: element: Human-readable element description used to obtain permission to interact with the element startX: Start X coordinate startY: Start Y coordinate endX: End X coordinate Read-only: false ``` -------------------------------- ### Electron `launch` Method API Reference Source: https://playwright.dev/docs/api/class-electron Detailed API documentation for the `electron.launch` method, including its parameters and their types, descriptions, and default values. This method is used to programmatically launch an Electron application with various configurable options, such as handling downloads, setting arguments, bypassing CSP, and emulating color schemes. ```APIDOC electron.launch(options?: object) options: object (optional) acceptDownloads?: boolean (v1.12) - Whether to automatically download all the attachments. Defaults to `true` where all the downloads are accepted. args?: Array (optional) - Additional arguments to pass to the application when launching. You typically pass the main script name here. bypassCSP?: boolean (v1.12) - Toggles bypassing page's Content-Security-Policy. Defaults to `false`. colorScheme?: null | "light" | "dark" | "no-preference" (v1.12) - Emulates prefers-colors-scheme media feature, supported values are 'light' and 'dark'. See page.emulateMedia() for more details. Passing `null` resets emulation to system defaults. Defaults to 'light'. cwd?: string (optional) - Current working directory to launch application from. env?: Object (optional) - Specifies environment variables that will be visible to Electron. Defaults to `process.env`. executablePath?: string (optional) - Launches given Electron application. If not specified, launches the default Electron executable installed in this package, located at `node_modules/.bin/electron`. extraHTTPHeaders?: Object (v1.12) - An object containing additional HTTP headers to be sent with every request. Defaults to none. geolocation?: object (v1.12) latitude: number - Latitude between -90 and 90. longitude: number - Longitude between -180 and 180. accuracy?: number (optional) - Non-negative accuracy value. Defaults to `0`. httpCredentials?: object (v1.12) username: string ``` -------------------------------- ### Move mouse Source: https://github.com/microsoft/playwright-mcp Move mouse to a given position ```APIDOC browser_screen_move_mouse(element: string, x: number, y: number) Description: Move mouse to a given position Parameters: element: Human-readable element description used to obtain permission to interact with the element x: X coordinate y: Y coordinate Read-only: true ``` -------------------------------- ### Puppeteer Main Class API Source: https://github.com/cloudflare/puppeteer/blob/main/docs/api/index The Puppeteer class serves as the main entry point for the Puppeteer library. No detailed description was provided in the source text. ```APIDOC Puppeteer Class: Description: No description provided in the source text. ``` -------------------------------- ### Capture Basic Screenshot with Cloudflare Browser Rendering API Source: https://context7_llms This snippet illustrates the fundamental usage of the `/screenshot` endpoint. It shows how to render simple HTML content ('Hello World!') and capture a screenshot, utilizing the `omitBackground` option to enable transparency in the output image. ```bash curl -X POST 'https://api.cloudflare.com/client/v4/accounts//browser-rendering/screenshot' \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d '{ "html": "Hello World!", "screenshotOptions": { "omitBackground": true } }' \ --output "screenshot.png" ``` ```typescript import Cloudflare from "cloudflare"; const client = new Cloudflare({ apiEmail: process.env["CLOUDFLARE_EMAIL"], // This is the default and can be omitted apiKey: process.env["CLOUDFLARE_API_KEY"], // This is the default and can be omitted }); const screenshot = await client.browserRendering.screenshot.create({ account_id: "account_id", }); console.log(screenshot.status); ``` -------------------------------- ### Drag mouse Source: https://github.com/microsoft/playwright-mcp Drag left mouse button. ```APIDOC browser_screen_drag: ``` -------------------------------- ### Resize browser window Source: https://github.com/microsoft/playwright-mcp Resize the browser window. ```APIDOC browser_resize(width: number, height: number) width: Width of the browser window height: Height of the browser window ```