exec() method lets you run custom code directly in the remote browser session.
Basic Usage
Copy
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:Copy
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
Copy
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
Copy
// 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()
Copy
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
Complex scraping logic
Complex scraping logic
Copy
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;
});
Custom waiting logic
Custom waiting logic
Copy
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.

