Skip to main content
Context methods for the Stagehand driver.

Lifecycle

newPage

Create a new page (tab) in the browser.
The new page is automatically set as the active page. Defaults to “about:blank” if no URL is provided.
Upstream docs
url
string
The URL to navigate to in the new page.
result
RemoteStagehandPage
Return value
await context.newPage();

pages

Get all open pages in the browser context.
Returns an array of all open pages, ordered from oldest to newest.
Upstream docs
result
RemoteStagehandPage[]
Return value
await context.pages();

close

Close the browser context and all associated pages.
This method:
  • Closes the CDP connection
  • Cleans up all pages
  • Clears all internal mappings
Note: This is typically called internally by stagehand.close(). You usually don’t need to call this directly.
Upstream docs
await context.close();

Other

activePage

Get the currently active page.
The active page is determined by:
  1. Most recently interacted with page
  2. Most recently created page if no interaction history
  3. undefined if all pages have been closed
Upstream docs
result
RemoteStagehandPage | undefined
Return value
await context.activePage();

setActivePage

Set a specific page as the active page.
This method:
  • Marks the page as most recently used
  • Brings the tab to the foreground (in headed mode)
  • Makes it the default page for subsequent operations
Note: Pass page.id from a RemoteStagehandPage instance.
Upstream docs
pageId
string
required
The ID of the page to set as active.
await context.setActivePage('...');

addInitScript

Inject JavaScript that runs before any page scripts on every navigation.
This method:
  • Runs at document start
  • Installs the script on all currently open pages
  • Replays it on every navigation of those pages
  • Automatically applies to any pages created after calling addInitScript()
Upstream docs
script
string | { path?: string; content?: string } | ((arg: Arg) => unknown)
required
The script to inject. Can be raw source code, a file reference, or a function.
arg
Arg
Extra data that is JSON-serialized and passed to your function.
await context.addInitScript(/* string | { path?: string; content?: string } | ((arg: Arg) => unknown) */);