Skip to main content
The exec() method lets you run custom code directly in the remote browser session.

Basic Usage

const result = await session.exec(async ({ page }) => {
  await page.goto('https://example.com');
  return await page.title();
});

console.log(result); // "Example Domain"

Available Context

Your function receives these objects:
await session.exec(async ({ page, browser, context, stagehand }, args) => {
  // page - current page
  // browser - browser instance
  // context - browser context
  // stagehand - AI methods
  // args - your custom arguments
});

Passing Arguments

const result = await session.exec(
  async ({ page }, args) => {
    await page.goto(args.url);
    await page.locator(args.selector).click();
    return await page.title();
  },
  { url: 'https://example.com', selector: 'button' }
);

Return Values

// Return any serializable value
const data = await session.exec(async ({ page }) => {
  return {
    url: page.url(),
    title: await page.title(),
    content: await page.locator('body').innerText()
  };
});

Using Stagehand in exec()

const products = await session.exec(async ({ page, stagehand }, args) => {
  await page.goto(args.url);

  // Use AI inside exec
  const data = await stagehand.extract(
    'Get all products',
    args.schema
  );

  return data;
}, {
  url: 'https://example.com/products',
  schema: z.array(z.object({ name: z.string(), price: z.number() }))
});

Use Cases

const data = await session.exec(async ({ page }) => {
  const results = [];

  // Pagination logic
  while (true) {
    const items = await page.locator('.item').allInnerTexts();
    results.push(...items);

    const nextBtn = page.locator('button.next');
    if (await nextBtn.isDisabled()) break;
    await nextBtn.click();
    await page.waitForLoadState('networkidle');
  }

  return results;
});
await session.exec(async ({ page }) => {
  // Wait for specific condition
  await page.waitForFunction(() => {
    return document.querySelectorAll('.loaded').length >= 10;
  });
});
Code runs in a sandboxed environment. External modules and file system access are not available.