Page
Learn about the Stagehand Page object and browser navigation
Overview
Thepage object is the main interface for interacting with browser pages in Stagehand. It provides standard browser automation capabilities for navigation, interaction, and page inspection.
Access the page object through your Stagehand instance:
Navigation Methods
goto()
Navigate the page to a URL and wait for a lifecycle state.null (e.g. data: URLs or same-document navigations).
The URL to navigate to. Can be absolute or relative.
When to consider navigation succeeded.Options:
"load"- Wait for the load event"domcontentloaded"- Wait for DOMContentLoaded event (default)"networkidle"- Wait for network to be idle
"domcontentloaded"Maximum time to wait for navigation in milliseconds.Default:
15000reload()
Reload the current page.null.
When to consider reload complete. See
goto() for options.Maximum time to wait for reload in milliseconds.Default:
15000Whether to bypass the browser cache.Default:
falsegoBack()
Navigate back in browser history.null.
When to consider navigation complete.
Maximum time to wait in milliseconds.Default:
15000goForward()
Navigate forward in browser history.null.
When to consider navigation complete.
Maximum time to wait in milliseconds.Default:
15000Page Information
url()
Get the current page URL (synchronous).title()
Get the current page title.Interaction Methods
click()
Click at absolute page coordinates.returnXpath is true, otherwise an empty string.
X coordinate in CSS pixels.
Y coordinate in CSS pixels.
Optional click configuration.
hover()
Hover at absolute page coordinates without clicking.returnXpath is true, otherwise an empty string.
X coordinate in CSS pixels.
Y coordinate in CSS pixels.
Optional hover configuration.
scroll()
Scroll at absolute page coordinates using mouse wheel events.returnXpath is true, otherwise an empty string.
X coordinate in CSS pixels where the scroll occurs.
Y coordinate in CSS pixels where the scroll occurs.
Horizontal scroll amount in pixels. Positive values scroll right.
Vertical scroll amount in pixels. Positive values scroll down.
Optional scroll configuration.
dragAndDrop()
Drag from one position to another using mouse events.returnXpath is true, otherwise empty strings.
Starting X coordinate in CSS pixels.
Starting Y coordinate in CSS pixels.
Ending X coordinate in CSS pixels.
Ending Y coordinate in CSS pixels.
Optional drag configuration.
type()
Type text into the page (dispatches keyboard events).The text to type.
Optional typing configuration.
keyPress()
Press a single key or key combination (keyDown then keyUp). Supports named keys, printable characters, and modifier combinations.The key or key combination to press. Supports printable characters (
"a", "1"), named keys ("Enter", "Tab", "Escape", "Backspace", "ArrowDown", etc.), and modifier combinations using + ("Cmd+A", "Ctrl+C", "Shift+Tab").Common modifier aliases like "Cmd", "Ctrl", "Alt", and "Option" are accepted. "Cmd" maps to Meta on Mac and Control elsewhere.Optional key press configuration.
locator()
Create a locator for querying elements.CSS selector or XPath for the element.
Locator object for interacting with the element.
Evaluation
evaluate()
Evaluate JavaScript code in the page context.JavaScript expression as a string or a function to execute in the page context.
Optional argument to pass to the function.
Initialization Scripts
addInitScript()
Inject JavaScript that runs before any of the page’s scripts on every navigation.Provide the script to inject. Pass raw source, reference a preload file on disk,
or supply a function that Stagehand serializes before sending to the browser.
Extra data that is JSON-serialized and passed to your function. Only supported
when
script is a function.- Runs at document start for the current page (including adopted iframe sessions) on every navigation
- Reinstalls the script for all future navigations of this page without affecting other pages
- Mirrors Playwright’s
page.addInitScript()ordering semantics; usecontext.addInitScript()to target every page in the context
HTTP Headers
setExtraHTTPHeaders()
Set HTTP headers that will be included in every request made by this page.A plain object of header name–value pairs. All values must be strings.
- Applies the headers to the page’s main CDP session and all of its child sessions (e.g. out-of-process iframes)
- Automatically applies the same headers to any child sessions adopted after calling
setExtraHTTPHeaders() - Calling it again replaces all previously set extra headers (it does not merge)
- To clear all extra headers, pass an empty object:
await page.setExtraHTTPHeaders({})
Headers set via
page.setExtraHTTPHeaders() are page-scoped. They apply to every network request from this page only, including navigation requests, XHR/fetch calls, and subresource loads. Use context.setExtraHTTPHeaders() to set headers across all pages in the context.Screenshot
screenshot()
Capture a screenshot of the page.Capture the entire scrollable page instead of just the current viewport.Default:
falseLimit the capture to the provided rectangle in CSS pixels (
{ x, y, width, height }).
Cannot be combined with fullPage.Image format for the screenshot.Default:
"png"JPEG quality (0–100). Only used when
type is "jpeg".Rendering scale. Use
"css" for one pixel per CSS pixel, or "device" for the
device pixel ratio.Default: "device"Control CSS/Web animations and transitions.
"disabled" fast-forwards finite
animations and pauses infinite ones before capture.Default: "allow"Hide the text caret during capture (
"hide") or leave it untouched ("initial").Default: "hide"List of locators to cover with a colored overlay while the screenshot is taken.
CSS color to use for masked overlays.Default:
#FF00FFAdditional CSS text injected into every frame just before capture. Useful for
hiding or tweaking dynamic UI.
Make the default page background transparent (PNG only).Default:
falseMaximum time in milliseconds to wait for the capture before throwing.
Write the screenshot to the provided file path. The image is still returned as
a buffer.
Promise<Buffer> containing the screenshot image data.
Page Snapshot
snapshot()
Capture a structured accessibility snapshot of the current page. The returned data combines a human-readable accessibility tree with lookup maps so you can relate each node to DOM selectors or URLs.Optional configuration for the snapshot.
Promise<SnapshotResult> describing the captured accessibility tree.
See SnapshotResult for the static type definition.
The formatted tree represents every accessibility node with:
- A unique encoded ID in brackets (e.g.,
[0-1]) for cross-referencing with the maps - The node’s accessibility role (
RootWebArea,heading,link,button, etc.) - The node’s accessible name, when available
WebMCP
listWebMCPTools()
List WebMCP tools registered by the current page.Optional configuration for collecting the current page’s tool snapshot.
Promise<WebMCPTool[]> snapshot from the browser. Each tool is identified by its name and frameId.
WebMCP requires Chrome or Chromium newer than version 149, and it must be launched with
--enable-features=WebMCPTesting,DevToolsWebMCPSupport. Stagehand launches browsers with those flags by default.invokeWebMCPTool()
Invoke a WebMCP tool registered by the current page.Name of the registered WebMCP tool to invoke.
JSON-serializable input passed to the tool.
Optional frame targeting and timeout configuration.
Promise<WebMCPToolInvocation>. The invocation object includes the browser invocationId, resolved toolName, resolved frameId, a result promise, and a cancel() function.
cancel() to request cancellation for a pending invocation:
Viewport
setViewportSize()
Set the page viewport size.Viewport width in CSS pixels.
Viewport height in CSS pixels.
Device scale factor (pixel ratio).Default:
1Wait Methods
waitForLoadState()
Wait for the page to reach a specific lifecycle state.The lifecycle state to wait for.Options:
"load", "domcontentloaded", "networkidle"Maximum time to wait in milliseconds.Default:
15000waitForSelector()
Wait for an element matching the selector to reach a specific state in the DOM. Uses a MutationObserver for efficiency, pierces shadow DOM by default, and supports iframe hops when needed.CSS selector or XPath expression to wait for. Supports iframe hops (e.g.,
/html/div/iframe/html/div/button).Optional wait configuration.
true when the condition is met.
Throws: Error if timeout is reached before the condition is met.
Events
on(“console”)
Listen for console output produced by the page and any adopted iframe sessions. Returns the page instance so calls can be chained.ConsoleMessage exposes helpers for working with console events:
message.type()– console API category such aslog,error, orwarningmessage.text()– string representation of the console argumentsmessage.args()– underlying CDPRemoteObjectarguments arraymessage.location()– source URL, line, and column when availablemessage.timestamp()– CDP timestamp for the eventmessage.raw()– access to the originalRuntime.consoleAPICalledEvent
once(“console”)
Register a listener that removes itself after the first console event.off(“console”)
Remove a previously registered listener. The reference must match the original listener passed toon().
Code Examples
Types
LoadState
"load"- Wait for theloadevent (all resources loaded)"domcontentloaded"- Wait for theDOMContentLoadedevent (DOM is ready)"networkidle"- Wait for network connections to be idle
AnyPage
AnyPage type represents any compatible page object.
ScreenshotClip
clip is provided.
ScreenshotOptions
PageSnapshotOptions
includeIframes- Whether to include iframe content in the snapshot. Defaults totrue
SnapshotResult
formattedTree- A formatted string representation of the page’s accessibility tree with encoded IDs, roles, and namesxpathMap- A mapping from encoded element IDs to their absolute XPath selectorsurlMap- A mapping from encoded element IDs to their associated URLs (for links and other navigable elements)
WebMCPTool
name- Tool name registered by the pagedescription- Optional description registered by the pageinputSchema- Optional input schema registered by the pageannotations- Optional annotations registered by the pageframeId- Browser frame ID where the tool was registered
WebMCPToolInvocationStatus
WebMCPToolResult
invocationId- Browser invocation ID for the tool callstatus- Final invocation statusoutput- Optional tool outputerrorText- Optional error text returned by the browserexception- Optional exception returned by the browser
WebMCPToolInvocation
invocationId- Browser invocation ID for the tool calltoolName- Tool name passed toinvokeWebMCPTool()frameId- Frame ID used for the invocationresult- Promise that resolves with the final tool result or rejects on timeout/disposalcancel- SendsWebMCP.cancelInvocationfor the pending invocation
WebMCPListToolsOptions
timeoutMs- Maximum time in milliseconds to wait for the tool snapshot. Defaults to1000
WebMCPToolInvocationOptions
frameId- Frame ID where the tool was registeredtimeoutMs- Maximum time in milliseconds to wait for the invocation result. Defaults to30000
Error Handling
Page methods may throw the following errors:- Navigation Errors - Timeout or network issues during navigation
- Evaluation Errors - JavaScript execution errors in
evaluate() - Interaction Errors - Failed clicks or typing operations
- Screenshot Errors - Issues capturing screenshots
- WebMCP Errors - Unsupported browser features, ambiguous tool names across frames, invocation result timeouts, or disposed pending invocations

