playwriter

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

playwriter - Playwright Browser Automation for AI Agents

playwriter - 面向AI Agent的Playwright浏览器自动化工具

Playwriter connects AI agents to your running Chrome browser instead of spawning a new headless instance. Your existing logins, cookies, extensions, and tab state are all preserved.
Playwriter可将AI Agent连接到您正在运行的Chrome浏览器,而非启动新的无头浏览器实例。您的现有登录信息、Cookie、扩展程序以及标签页状态都会被保留。

When to use this skill

何时使用该工具

  • Automate sites that require login (Gmail, GitHub, internal tools) without re-authenticating
  • Control your real browser tab with full Playwright API access
  • Run stateful automation that spans multiple steps (shopping carts, multi-step forms)
  • Use MCP integration for Claude Desktop / AI agent browser control
  • Record browser sessions or debug with CDP inspection
  • Remote browser automation via tunnels
vs. agent-browser: agent-browser spawns a fresh headless browser (isolated, CI-friendly). playwriter connects to your existing Chrome session (authenticated, stateful, with your extensions).
  • 无需重新验证即可实现需登录网站(如Gmail、GitHub、内部工具)的自动化操作
  • 通过完整的Playwright API访问控制真实浏览器标签页
  • 运行跨多步骤的有状态自动化任务(如购物车操作、多步骤表单填写)
  • 集成MCP以实现Claude Desktop / AI Agent浏览器控制
  • 录制浏览器会话或通过CDP检查进行调试
  • 通过隧道实现远程浏览器自动化
与agent-browser的对比:agent-browser会启动全新的无头浏览器(隔离环境,适合CI场景)。playwriter则连接到您现有的Chrome会话(已验证状态、有状态、包含您的扩展程序)。

Installation

安装步骤

Step 1: Install Chrome Extension

步骤1:安装Chrome扩展程序

Install the Playwriter Chrome extension from the Web Store (search "Playwriter MCP" or use extension ID
jfeammnjpkecdekppnclgkkffahnhfhe
).
After installing, click the extension icon on any tab you want to allow automation on. The icon turns green when a tab is enabled for control.
从Chrome网上应用店安装Playwriter扩展程序(搜索"Playwriter MCP"或使用扩展程序ID
jfeammnjpkecdekppnclgkkffahnhfhe
)。
安装完成后,在您想要允许自动化操作的任意标签页上点击扩展程序图标。当标签页已启用控制时,图标会变为绿色

Step 2: Install CLI

步骤2:安装CLI

bash
npm install -g playwriter
bash
npm install -g playwriter

or run without installing:

或无需安装直接运行:

npx playwriter@latest --help

The extension auto-starts a WebSocket relay server at `localhost:19988`.
npx playwriter@latest --help

扩展程序会自动在 `localhost:19988` 启动一个WebSocket中继服务器。

Core workflow

核心工作流

Always follow the Observe → Act → Observe pattern:
bash
undefined
请始终遵循“观察 → 操作 → 观察”的模式:
bash
undefined

1. Create a session

1. 创建会话

playwriter session new
playwriter session new

2. Navigate and observe

2. 导航并观察

playwriter -s 1 -e 'await page.goto("https://example.com")' playwriter -s 1 -e 'await snapshot({ page })'
playwriter -s 1 -e 'await page.goto("https://example.com")' playwriter -s 1 -e 'await snapshot({ page })'

3. Interact based on snapshot output

3. 根据快照输出进行交互

playwriter -s 1 -e 'await page.locator("aria-ref=e5").click()'
playwriter -s 1 -e 'await page.locator("aria-ref=e5").click()'

4. Re-observe after action

4. 操作后重新观察

playwriter -s 1 -e 'await snapshot({ page })'
undefined
playwriter -s 1 -e 'await snapshot({ page })'
undefined

Session management

会话管理

bash
undefined
bash
undefined

Create a new isolated stateful session

创建新的隔离有状态会话

playwriter session new
playwriter session new

List all active sessions (shows browser, profile, state info)

列出所有活跃会话(显示浏览器、配置文件、状态信息)

playwriter session list
playwriter session list

Delete a session and clear its state

删除会话并清除其状态

playwriter session delete <sessionId>
playwriter session delete <sessionId>

Reset the CDP connection and clear execution environment

重置CDP连接并清除执行环境

playwriter session reset <sessionId>
undefined
playwriter session reset <sessionId>
undefined

The -e / --eval flag

-e / --eval 参数

Execute arbitrary Playwright code in a session:
bash
undefined
在会话中执行任意Playwright代码:
bash
undefined

Navigate to a URL

导航到指定URL

playwriter -s 1 -e 'await page.goto("https://github.com")'
playwriter -s 1 -e 'await page.goto("https://github.com")'

Fill a form field

填写表单字段

playwriter -s 1 -e 'await page.fill("#search", "playwriter"); await page.keyboard.press("Enter")'
playwriter -s 1 -e 'await page.fill("#search", "playwriter"); await page.keyboard.press("Enter")'

Get accessibility snapshot (preferred over screenshots for text content)

获取无障碍快照(对于文本内容检查,优先于截图)

playwriter -s 1 -e 'await snapshot({ page })'
playwriter -s 1 -e 'await snapshot({ page })'

Take screenshot with visual accessibility labels (color-coded by element type)

生成带有无障碍标签的截图(按元素类型进行颜色编码)

playwriter -s 1 -e 'await screenshotWithAccessibilityLabels({ page })'
playwriter -s 1 -e 'await screenshotWithAccessibilityLabels({ page })'

Store state between calls (state object persists within session)

在多次调用之间存储状态(state对象在同一会话中会持续保留)

playwriter -s 1 -e 'state.url = page.url(); state.title = await page.title()' playwriter -s 1 -e 'console.log(state.url, state.title)'

**Quoting rules**: Wrap code in single quotes. For multiline code, use heredoc:

```bash
playwriter -s 1 -e "$(cat <<'EOF'
const text = await page.textContent('h1');
state.heading = text;
await snapshot({ page });
EOF
)"
playwriter -s 1 -e 'state.url = page.url(); state.title = await page.title()' playwriter -s 1 -e 'console.log(state.url, state.title)'

**引号规则**:将代码包裹在单引号中。对于多行代码,使用here文档:

```bash
playwriter -s 1 -e "$(cat <<'EOF'
const text = await page.textContent('h1');
state.heading = text;
await snapshot({ page });
EOF
)"

MCP Integration

MCP集成

Claude Desktop config (
~/.claude/settings.json
or Claude Desktop MCP settings)

Claude Desktop配置(
~/.claude/settings.json
或 Claude Desktop MCP设置)

json
{
  "mcpServers": {
    "playwriter": {
      "command": "npx",
      "args": ["-y", "playwriter@latest"]
    }
  }
}
json
{
  "mcpServers": {
    "playwriter": {
      "command": "npx",
      "args": ["-y", "playwriter@latest"]
    }
  }
}

Remote relay server

远程中继服务器

json
{
  "mcpServers": {
    "playwriter": {
      "command": "npx",
      "args": ["-y", "playwriter@latest"],
      "env": {
        "PLAYWRITER_HOST": "your-relay-host",
        "PLAYWRITER_TOKEN": "your-secret-token",
        "PLAYWRITER_SESSION": "1"
      }
    }
  }
}
json
{
  "mcpServers": {
    "playwriter": {
      "command": "npx",
      "args": ["-y", "playwriter@latest"],
      "env": {
        "PLAYWRITER_HOST": "your-relay-host",
        "PLAYWRITER_TOKEN": "your-secret-token",
        "PLAYWRITER_SESSION": "1"
      }
    }
  }
}

MCP tools exposed

暴露的MCP工具

ToolDescription
execute
Run arbitrary JavaScript Playwright code (
code
,
timeout
params)
reset
Recreate CDP connection, clear state — use after connection failures
工具描述
execute
运行任意JavaScript Playwright代码(参数包含
code
timeout
reset
重新创建CDP连接,清除状态 —— 连接失败后使用

Built-in globals (in execute sandbox)

内置全局变量(在execute沙箱中)

GlobalDescription
page
Current Playwright page
context
Browser context
state
Persistent object — survives multiple
-e
calls in same session
snapshot({ page })
Accessibility tree as text (token-efficient)
screenshotWithAccessibilityLabels({ page })
Screenshot with color-coded element markers
getPageMarkdown()
Article text via Mozilla Readability
waitForPageLoad()
Smart load detection
getLatestLogs()
Browser console errors/logs
getCleanHTML()
Cleaned DOM HTML
getLocatorStringForElement()
Get selector for a DOM element
getReactSource()
React component source tree
全局变量描述
page
当前Playwright页面
context
浏览器上下文
state
持久化对象 —— 在同一会话的多次
-e
调用中会保留
snapshot({ page })
以文本形式呈现的无障碍树(Token效率更高)
screenshotWithAccessibilityLabels({ page })
带有颜色编码元素标记的截图
getPageMarkdown()
通过Mozilla Readability获取文章文本
waitForPageLoad()
智能加载检测
getLatestLogs()
浏览器控制台错误/日志
getCleanHTML()
清理后的DOM HTML
getLocatorStringForElement()
获取DOM元素的选择器
getReactSource()
React组件源码树

Accessibility labeling

无障碍标签

screenshotWithAccessibilityLabels({ page })
overlays color-coded markers on interactive elements:
ColorElement type
YellowLinks
OrangeButtons
CoralInputs
PinkCheckboxes
PeachSliders
Click a labeled element using
aria-ref
:
bash
playwriter -s 1 -e 'await page.locator("aria-ref=e5").click()'
screenshotWithAccessibilityLabels({ page })
会在交互元素上叠加颜色编码标记:
颜色元素类型
黄色链接
橙色按钮
珊瑚色输入框
粉色复选框
桃色滑块
使用
aria-ref
点击带标签的元素:
bash
playwriter -s 1 -e 'await page.locator("aria-ref=e5").click()'

Network interception and state persistence

网络拦截与状态持久化

bash
undefined
bash
undefined

Intercept network requests

拦截网络请求

playwriter -s 1 -e 'state.requests = []; page.on("request", r => state.requests.push(r.url()))'
playwriter -s 1 -e 'state.requests = []; page.on("request", r => state.requests.push(r.url()))'

Check collected requests later

稍后查看收集到的请求

playwriter -s 1 -e 'console.log(state.requests.slice(-5).join("\n"))'
playwriter -s 1 -e 'console.log(state.requests.slice(-5).join("\n"))'

Screen recording

屏幕录制

playwriter -s 1 -e 'await recording.start()'
playwriter -s 1 -e 'await recording.start()'

... do actions ...

...执行操作...

playwriter -s 1 -e 'const video = await recording.stop(); state.video = video'
undefined
playwriter -s 1 -e 'const video = await recording.stop(); state.video = video'
undefined

Remote access

远程访问

Control Chrome on a remote machine via tunnel:
bash
undefined
通过隧道控制远程机器上的Chrome浏览器:
bash
undefined

On the machine with Chrome:

在运行Chrome的机器上:

playwriter serve --token my-secret --replace
playwriter serve --token my-secret --replace

From agent machine:

在Agent机器上:

playwriter --host <ip-or-hostname> --token my-secret -s 1 -e 'await page.goto("https://example.com")'
undefined
playwriter --host <ip-or-hostname> --token my-secret -s 1 -e 'await page.goto("https://example.com")'
undefined

Best practices

最佳实践

  • Observe → Act → Observe: always call
    snapshot({ page })
    before and after each action
  • Prefer
    snapshot()
    over screenshots
    for text inspection (fewer tokens, faster)
  • Never chain actions blindly — verify state between steps
  • Use stable selectors: prefer
    aria-ref
    ,
    data-testid
    , or accessible roles
  • Store context in
    state
    : avoid repeated navigation by persisting page references
  • Use
    reset
    on failures
    : CDP disconnects recover cleanly with
    playwriter session reset
  • 观察 → 操作 → 观察:每次操作前后务必调用
    snapshot({ page })
  • 优先使用
    snapshot()
    而非截图
    进行文本检查(Token更少、速度更快)
  • 切勿盲目链式执行操作 —— 在步骤之间验证状态
  • 使用稳定选择器:优先选择
    aria-ref
    data-testid
    或无障碍角色
  • 将上下文存储在
    state
    :通过持久化页面引用避免重复导航
  • 失败时使用
    reset
    :CDP断开连接后,使用
    playwriter session reset
    可干净地恢复连接

Troubleshooting

故障排除

IssueSolution
Extension not connectingClick extension icon on the tab; icon must be green
connection refused :19988
Extension auto-starts server; check Chrome is running with extension installed
Code execution timeoutIncrease with
--timeout 30000
flag
Click fails silentlyUse
snapshot({ page })
— a modal likely intercepts the click
Stale sessionRun
playwriter session reset <id>
to restore CDP connection
Remote access failingConfirm
playwriter serve
is running and token matches
问题解决方案
扩展程序无法连接点击标签页上的扩展程序图标;图标必须为绿色
connection refused :19988
扩展程序会自动启动服务器;检查Chrome是否已安装扩展程序并运行
代码执行超时使用
--timeout 30000
参数增加超时时间
点击操作无响应使用
snapshot({ page })
检查 —— 可能有模态框拦截了点击
会话失效运行
playwriter session reset <id>
以恢复CDP连接
远程访问失败确认
playwriter serve
正在运行且令牌匹配

References

参考资料