Skip to main content

网络与模拟

🌐 Network & Mocking

检查网络流量、模拟 API 响应,并测试离线行为。检查请求是 核心 的一部分,始终可用。模拟和网络状态控制需要 网络 功能

🌐 Inspect network traffic, mock API responses, and test offline behavior. Inspecting requests is part of core and always available. Mocking and network state control require the network capability.

{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest", "--caps=network"]
}
}
}

检查网络请求

🌐 Inspect network requests

browser_network_requests

返回自页面加载以来的网络请求编号列表。属于 核心 — 不需要额外权限。

🌐 Returns a numbered list of network requests since loading the page. Part of core — no extra capability needed.

参数类型必填描述
static布尔值是否包含成功的静态资源,如图片、字体和脚本。默认是 false
filter字符串仅返回 URL 与此正则表达式匹配的请求,例如 /api/.*user
filename字符串将列表保存到文件,而不是作为文本返回
→ browser_network_requests { filter: "api" }

1. [GET] https://api.example.com/me => [200] OK
2. [POST] https://api.example.com/users/create => [201] Created
3. [GET] https://api.example.com/settings => [200] OK

Note: 14 static requests not shown, run with "static" option to see them.

browser_network_request

返回单个请求的完整详情——包括一般信息、头信息和正文——使用 browser_network_requests 打印的编号。

🌐 Returns full details — general info, headers and bodies — of a single request, using the number printed by browser_network_requests.

参数类型必填描述
index数字请求的从1开始的索引
part字符串只返回这部分:request-headersrequest-bodyresponse-headersresponse-body
filename字符串将输出保存到文件,而不是以文本形式返回
→ browser_network_request { index: 2 }

#2 [POST] https://api.example.com/users/create

General
status: [201] Created
duration: 45ms
type: fetch
mimeType: application/json

Request headers
content-type: application/json
...

Response headers
content-type: application/json
...

Call browser_network_request with part="request-body" to read the request body.
Call browser_network_request with part="response-body" to read the response body.

→ browser_network_request { index: 2, part: "response-body" }

{"id":42,"name":"Alice"}

二进制响应体会写入输出目录,工具会返回文件路径。

🌐 Binary response bodies are written to the output directory and the tool returns the file path.

模拟 API 响应

🌐 Mock API responses

browser_route

设置一个用于模拟匹配特定 URL 模式的网络请求的路由。当提供 statusbody 时,请求将使用该响应完成;否则请求将继续进行,并应用头部修改。

🌐 Set up a route to mock network requests matching a URL pattern. When status or body is given the request is fulfilled with that response; otherwise the request continues with the header modifications applied.

参数类型必填说明
pattern字符串要匹配的 URL 模式,例如 **/api/users**/*.{png,jpg}
status数字要返回的 HTTP 状态码(默认 200)
body字符串响应体(文本或 JSON 字符串)
contentType字符串Content-Type 头,例如 application/json
headers字符串数组要添加到请求的头,格式为 "Name: Value"
removeHeaders字符串要从请求中删除的头名称,使用逗号分隔列表

模拟一个 API 端点

🌐 Mock an API endpoint

You: Mock the /api/users endpoint to return two test users.

→ browser_route {
pattern: "**/api/users",
status: 200,
body: "[{\"id\":1,\"name\":\"Alice\"},{\"id\":2,\"name\":\"Bob\"}]",
contentType: "application/json"
}
→ browser_navigate { url: "https://app.example.com/users" }

- heading "Users" [level=1] [ref=e2]
- list [ref=e4]:
- listitem [ref=e5]: Alice
- listitem [ref=e6]: Bob

测试错误处理

🌐 Test error handling

You: Test what happens when the API returns a 503 error.

→ browser_route { pattern: "**/api/users", status: 503 }
→ browser_navigate { url: "https://app.example.com/users" }

- heading "Something went wrong" [level=1] [ref=e2]
- button "Retry" [ref=e5]

→ browser_take_screenshot

去掉模拟并验证恢复:

🌐 Remove the mock and verify recovery:

→ browser_unroute
→ browser_click { target: "e5" }

- heading "Users" [level=1] [ref=e2]

阻止资源

🌐 Block resources

→ browser_route { pattern: "**/*.jpg", status: 404 }
→ browser_route { pattern: "**/analytics/**", status: 204 }

添加或移除请求头

🌐 Add or strip request headers

→ browser_route { pattern: "**/api/**", headers: ["X-Debug: 1"] }
→ browser_route { pattern: "**/api/**", removeHeaders: "cookie,authorization" }

带条件的代码模拟

🌐 Conditional mocking with code

对于复杂的场景——延迟、条件响应、请求体检查——使用 browser_run_code_unsafe

🌐 For complex scenarios — delays, conditional responses, request body inspection — use browser_run_code_unsafe:

→ browser_run_code_unsafe {
code: "async (page) => {
await page.route('**/api/search', async route => {
const url = new URL(route.request().url());
const query = url.searchParams.get('q');
await route.fulfill({
body: JSON.stringify(query === 'empty' ? [] : [{ title: 'Result: ' + query }])
});
});
}"
}

管理路由

🌐 Manage routes

browser_route_list

列出所有活动路由。不需要参数。

🌐 Lists all active routes. Takes no parameters.

→ browser_route_list

1. **/api/users (status=200, body=[{"id":1,"name":"Alice"}]..., contentType=application/json)
2. **/*.jpg (status=404)
3. **/analytics/** (status=204)

browser_unroute

参数类型必填描述
pattern字符串要取消路由的 URL 模式。不填则移除所有路由

测试离线模式

🌐 Test offline mode

browser_network_state_set

设置浏览器的网络状态。离线时,所有网络请求都会失败。

🌐 Sets the browser network state. When offline, all network requests fail.

参数类型是否必需描述
state字符串onlineoffline
→ browser_network_state_set { state: "offline" }
→ browser_navigate { url: "https://app.example.com" }

- heading "No internet connection" [level=1] [ref=e2]

→ browser_network_state_set { state: "online" }

限制来源

🌐 Restricting origins

不考虑模拟,服务器可以被告知浏览器可以访问哪些来源:

🌐 Independently of mocking, the server can be told which origins the browser may reach at all:

["@playwright/mcp@latest", "--allowed-origins=https://example.com;http://localhost:*"]
["@playwright/mcp@latest", "--blocked-origins=https://ads.example.com"]

两者都接受用分号分隔的列表,并且先评估黑名单。这些只是方便的保护措施,不是安全边界——它们不会影响重定向。

🌐 Both take semicolon-separated lists, and the blocklist is evaluated first. These are convenience guardrails, not a security boundary — they do not affect redirects.