Skip to main content

Code Execution

Run Playwright code and evaluate JavaScript for interactions that go beyond individual tool calls.

browser_run_code_unsafe

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.

ParameterTypeRequiredDescription
codestringnoA JavaScript function containing Playwright code to execute
filenamestringnoLoad the code from this file instead. Relative names resolve against the workspace root. If both are provided, code is ignored
warning

This tool executes arbitrary JavaScript in the Playwright server process and is RCE-equivalent.

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"

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

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.

ParameterTypeRequiredDescription
functionstringyes() => { /* code */ }, or (element) => { /* code */ } when target is provided
targetstringnoElement ref or selector to evaluate on
filenamestringnoSave the result to a file instead of returning it as text
→ 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

ScenarioUse
Click a buttonbrowser_click
Fill a form fieldbrowser_type or browser_fill_form
Read element textbrowser_snapshot or browser_find
Check computed stylesbrowser_evaluate
Complex multi-step logicbrowser_run_code_unsafe
Geolocation/permissionsbrowser_run_code_unsafe
Custom wait conditionsbrowser_run_code_unsafe
Iframe interactionsbrowser_run_code_unsafe