代码执行
🌐 Code Execution
运行 Playwright 代码并评估 JavaScript,以处理超出单个工具调用的交互。
🌐 Run Playwright code and evaluate JavaScript for interactions that go beyond individual tool calls.
browser_run_code_unsafe
运行一个 Playwright 代码片段。该代码是一个 JavaScript 函数,通过单个 page 参数调用,可以访问完整的 Playwright API。它的返回值会被序列化回工具响应中。
🌐 Run a Playwright code snippet. The code is a JavaScript function invoked with a single page
argument, giving access to the full Playwright API. Its return value is
serialized back into the tool response.
| 参数 | 类型 | 必填 | 描述 |
|---|---|---|---|
code | string | 否 | 包含要执行的 Playwright 代码的 JavaScript 函数 |
filename | string | 否 | 从这个文件加载代码。相对路径相对于工作区根目录解析。如果两个都提供,则忽略 code |
这个工具可以在 Playwright 服务器进程中执行任意 JavaScript,相当于远程代码执行(RCE)。
验证元素内容
🌐 Verify element content
→ browser_run_code_unsafe {
code: "async (page) => { return await page.getByTestId('todo-count').textContent(); }"
}
"3 items left"
设置地理位置
🌐 Set geolocation
→ browser_run_code_unsafe {
code: "async (page) => { await page.context().grantPermissions(['geolocation']); await page.context().setGeolocation({ latitude: 37.7749, longitude: -122.4194 }); }"
}
等待特定条件
🌐 Wait for a specific condition
→ browser_run_code_unsafe {
code: "async (page) => { await page.waitForSelector('.loading', { state: 'hidden' }); return 'Loading complete'; }"
}
"Loading complete"
处理 iframes
🌐 Handle iframes
→ browser_run_code_unsafe {
code: "async (page) => { const frame = page.frameLocator('#payment-iframe'); return await frame.locator('.total').textContent(); }"
}
"$49.99"
剪贴板操作
🌐 Clipboard operations
→ browser_run_code_unsafe {
code: "async (page) => { await page.context().grantPermissions(['clipboard-read', 'clipboard-write']); return await page.evaluate(() => navigator.clipboard.readText()); }"
}
运行文件中的代码片段
🌐 Run a snippet from a file
→ browser_run_code_unsafe { filename: "scripts/seed-cart.js" }
browser_evaluate
在页面上或特定元素上评估一个 JavaScript 表达式。和 browser_run_code_unsafe 不同,这段代码是在页面内部运行的,而不是在服务器进程中。
🌐 Evaluate a JavaScript expression on the page, or on a specific element. Unlike
browser_run_code_unsafe, the code runs inside the page, not in the server process.
| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
function | 字符串 | 是 | 当提供 target 时为 (element) => { /* code */ },否则为 () => { /* code */ } |
target | 字符串 | 否 | 要评估的元素引用或选择器 |
filename | 字符串 | 否 | 将结果保存到文件,而不是作为文本返回 |
→ browser_evaluate { function: "() => document.title" }
"TodoMVC - React"
→ browser_evaluate { function: "element => element.getAttribute('data-testid')", target: "e15" }
"submit-button"
→ browser_evaluate { function: "() => window.innerWidth + 'x' + window.innerHeight" }
"1280x720"
何时使用代码执行
🌐 When to use code execution
| 场景 | 用途 |
|---|---|
| 点击按钮 | browser_click |
| 填写表单字段 | browser_type 或 browser_fill_form |
| 读取元素文本 | browser_snapshot 或 browser_find |
| 检查计算样式 | browser_evaluate |
| 复杂多步骤逻辑 | browser_run_code_unsafe |
| 地理位置/权限 | browser_run_code_unsafe |
| 自定义等待条件 | browser_run_code_unsafe |
| Iframe 交互 | browser_run_code_unsafe |