Skip to main content

代码执行

🌐 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.

参数类型必填描述
codestring包含要执行的 Playwright 代码的 JavaScript 函数
filenamestring从这个文件加载代码。相对路径相对于工作区根目录解析。如果两个都提供,则忽略 code
warning

这个工具可以在 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_typebrowser_fill_form
读取元素文本browser_snapshotbrowser_find
检查计算样式browser_evaluate
复杂多步骤逻辑browser_run_code_unsafe
地理位置/权限browser_run_code_unsafe
自定义等待条件browser_run_code_unsafe
Iframe 交互browser_run_code_unsafe