Playwright Extensions
This chapter introduces the extension features of the Playwright ecosystem, including the Library script mode, MCP services, Test Agents, and a guide for migrating from other frameworks to Playwright.
* * *
## Playwright Library Script Mode
Playwright Library is a standalone browser automation library, suitable for scenarios outside of test runners.
### Installation
npm i playwright
### Typical Usage
## Example
// Screenshot script
import{ chromium } from 'playwright';
(async ()=>{
const browser = await chromium.launch({ headless:true});
const page = await browser.newPage();
await page.goto('');
await page.screenshot({ path:'tutorial.png', fullPage:true});
await browser.close();
console.log('Screenshot saved to tutorial.png');
})();
### PDF Generation
## Example
import{ chromium } from 'playwright';
(async ()=>{
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('');
// Generate PDF (only supported by Chromium)
await page.pdf({
path:'tutorial.pdf',
format:'A4',
margin:{ top:'20px', bottom:'20px'},
});
await browser.close();
})();
### Library Mode vs Test Runner Selection
| Scenario | Recommendation |
| --- | --- |
| Writing E2E tests | Playwright Test Runner |
| Webpage screenshots, generating PDFs | Playwright Library |
| Web data scraping | Playwright Library |
| One-off automation scripts | Playwright Library |
* * *
## Playwright MCP Introduction
The Playwright MCP (Model Context Protocol) server allows AI assistants to directly control the browser.
### MCP Installation and Configuration
# Add Playwright MCP for Claude Code claude mcp add playwright npx @playwright/mcp@latest
Configure in VS Code or other MCP clients:
## Example
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"]
}
}
}
### How MCP Works
AI Agents perceive page content through structured Accessibility Snapshots.
Each piece of accessibility information has a `ref` identifier, and the Agent uses this ref to perform actions like clicking and typing.
This approach does not require screenshots; it is entirely based on structured data interaction, which is fast and highly deterministic.
* * *
## Playwright Test Agents
Test Agents are experimental AI-driven testing tools that can automatically generate and fix tests.
| Agent | Function | Trigger Method |
| --- | --- | --- |
| Planner | Automatically explores the application, generates Markdown test plans | LLM Agent driven |
| Generator | Converts test plans into Playwright test code | LLM Agent driven |
| Healer | Executes test suites, automatically fixes failed tests | LLM Agent driven |
Initialize Test Agents:
# Initialize for VS Code npx playwright init-agents --loop=vscode # Initialize for Claude Code npx playwright init-agents --loop=claude
* * *
## Component Testing Overview (Experimental)
Playwright supports directly mounting and testing React/Vue components without requiring a full page environment.
## Example
test('Button component test', async ({ mount })=>{
// Mount React component
const component = await mount(
);
// Assert the text displayed by the component
await expect(component).toContainText('Submit');
// Click the button
await component.click();
});
* * *
## Accessibility Testing
Playwright provides assertions for accessible names and descriptions, helping to verify the accessibility of the page.
## Example
// Verify element has the correct accessible name
await expect(page.getByRole('button'))
.toHaveAccessibleName('Submit form');
// Verify element has an accessible description
await expect(page.getByLabel('Username'))
.toHaveAccessibleDescription('Please enter a 4-16 character alphanumeric combination');
* * *
## Migrating from Other Frameworks
### Migrating from Puppeteer
Playwright shares the Chrome DevTools Protocol capabilities with Puppeteer, making migration relatively simple.
| Puppeteer | Playwright |
| --- | --- |
| `puppeteer.launch()` | `chromium.launch()` |
| `page.waitForSelector()` | Not needed (auto-wait) or `page.locator()` |
| `page.$(selector)` | `page.locator(selector)` |
| `page.evaluate()` | `page.evaluate()` (same) |
| `page.setRequestInterception()` | `page.route()` |
### Migrating from Cypress
Playwright's Locator concept is similar to Cypress's query chains, but with some key differences:
| Cypress | Playwright |
| --- | --- |
| `cy.get('.class')` | `page.locator('.class')` |
| `cy.contains('text')` | `page.getByText('text')` |
| `cy.get('')` | `page.getByTestId('btn')` (with `testIdAttribute: 'data-cy'`) |
| `cy.intercept()` | `page.route()` |
| `cy.wait()` | Not needed (auto-wait) |
### Migrating from Selenium
Selenium uses the WebDriver protocol, while Playwright directly controls the browser protocol, resulting in significant API style differences.
| Selenium | Playwright |
| --- | --- |
| `driver.findElement(By.id('x'))` | `page.locator('#x')` |
| `driver.get(url)` | `page.goto(url)` |
| `element.click()` | `locator.click()` |
| `WebDriverWait` | Not needed (built-in auto-wait) |
| `new RemoteWebDriver()` | `chromium.connect(url)` |
> Migration advice: Do not attempt to migrate all tests at once.
>
>
> First, choose one or two core feature tests to rewrite with Playwright, and after verifying they pass, gradually migrate the remaining tests.
YouTip